所以我有一个普通的文本文件,其中包含一些写入内容,它实际上是随机的,但我也有一个单词列表,我想与之比较并计算出现在文本文件中的每个单词的出现次数单词列表。
例如,我的单词列表可以由以下内容组成:
good
bad
cupid
banana
apple
然后我想将每个单词与我的html / text文件进行比较,这可能是这样的:
有时候我会前往好的地方,而不是坏的地方。例如,我想去天堂,遇到一个吃苹果的丘比特。也许我会看到神话中的生物吃其他水果,如苹果,香蕉和其他好果子。
我希望我的输出能够生成列出的单词每次出现的次数。我有办法用for循环来做这个,但我真的希望避免for循环,因为它将需要永远,因为我的真实单词列表大约10000字长。
所以在这种情况下,我的输出应该是(我认为)9,因为它会计算该列表中一个单词的总出现次数。
此外,如果有办法显示匹配的单词和出现的次数,那将更有帮助。
答案 0 :(得分:0)
$words = '...'; // fill these with your stuff
$text = '...';
// split the word list
$expr = explode("\n", $words);
// sanitize the words contained
$expr = array_map(function ($v) { return preg_quote(trim($v)); }, $expr);
// prepare words for use in regex
$expr = '/('. implode('|', $expr) . ')/i'; // remove "i" for case sensitiviy
// matex prepared words against provided text
preg_match_all($expr, $text, $matches);
// calculate result
echo 'Count: ' . count($matches[1]);
答案 1 :(得分:0)
$text = 'Sometimes I travel to the good places that are good, and never the bad places that are bad. For example I want to visit the heavens and meet a cupid eating an apple. Perhaps I will see mythological creatures eating other fruits like apples, bananas, and other good fruits.';
preg_match_all('/good|bad|cupid|banana|apple/', $text, $matches);
// ECHO OUT NUMBER OF MATCHES
echo sizeof($matches[0]); // 9
// TO SHOW ALL MATCHES
print_r( $matches );