簡體   English   中英

從數組中查找一個值及其在PHP文本文件中的對應鍵

[英]From an array, lookup a value and it's corresponding key in a text file in PHP

我有一個較大的txt文件(3.5 MB),其結構如下:

sweep#1 expanse#1   0.375
loftiness#1 highness#2  0.375
lockstep#1  0.25
laziness#2  0.25
treponema#1 0.25
rhizopodan#1 rhizopod#1 0.25
plumy#3 feathery#3 feathered#1  -0.125
ruffled#2 frilly#1 frilled#1    -0.125
fringed#2   -0.125
inflamed#3  -0.125
inlaid#1    -0.125

每個單詞后跟一個# ,一個整數,然后是其“分數”。 單詞和分數之間有制表符。 到目前為止,文本文件已使用file_get_contents()作為字符串加載。

需要從由單個小寫字母字符分隔的單詞組成的字符串數組中 查找每個值,找到其對應的分數並將其添加到運行總計中

我想我需要某種形式的正則表達式來首先找到單詞,繼續到下一個\\t然后將整數添加到運行總計中。 最好的方法是什么?

是的,可能有更好的方法可以做到這一點。 但這是如此簡單:

<?php

$wordlist = file_get_contents("wordlist.txt");

//string string of invalid chars and make it lowercase
$string = "This is the best sentence ever! Winning!";
$string = strtolower($string);
$string = preg_replace('/[^\w\d_ -]/si', '', $string);
$words = explode(" ", $string);

$lines = explode("\n", $wordlist);
$scores = array();
foreach ($lines as $line) {
    $split = preg_split("/(\#|\t)/", $line); //split on # or tab
    $scores[$split[0]] = doubleval(array_pop($split));
    //split[0] (first element) contains the word
    //array_pop (last element) contains score
}

$total = 0;
foreach($words as $word) {
    if (isset($scores[$word])) $total += $scores[$word];
}

echo $total;
?>

如果您只需要查找一個單詞,那么它很簡單:

preg_match("/^$word#\d+\t+(\d+\.\d+)/m", $textfile, $match);
$sum += floatval($match[1]);

^/m模式下查找行的開頭, #\\t是文字分隔符,而\\d+匹配小數。 結果組[1]將是您的浮點數。

$word需要轉義(preg_quote),如果它本身可能包含/正斜杠。 要一次搜索多個單詞,將其內爆,作為替代列表$word1|$word2|$word3 ,添加一個捕獲組,並改用preg_match_all

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM