最好是 PHP 解决方案——但任何想法都会很棒。
给一个文本块
'这是一个超级串的一些内容,我想找到红色毛衣和紫色大象。紫色的大象会计数两次。因为红色毛衣出现了 3 次,所以红色毛衣会计算 3 次'
和一个词组列表
“红色毛衣,紫色大象”
想要搜索文本 blob 并返回出现次数
所以
红色毛衣 = 3 紫色大象 = 2
http://www.php.net/manual/en/function.substr-count.php
$string = 'This is a super string of some content whree I want to find red sweaters and purple elephants. The purple elephants will count twice. and the red sweaters will count 3 times since red sweaters occurs three times';
$keys = 'red sweaters, purple elephants';
$pkeys = explode(', ', $keys);
foreach($pkeys as $key)
{
printf("%s occourrences: %d\n", $key, substr_count($string, $key));
}
您可以使用substr_count来搜索文本中的字符串。请注意,在您的示例中,如果文本是“棕色毛衣”,则“红色毛衣”将计为 +1。
您还可以使用正则表达式。类似的东西preg_match("/$string/",$text);
。这将返回找到字符串的时间。
此外,如果您想搜索由逗号分隔的多个字符串(如您的示例),您首先需要拆分字符串。您可以为此使用爆炸。$strings = explode(",",$search);
像这样的东西应该工作:
<?php
$string = strtolower('This is a super string of some content whree I want to find red sweaters and purple elephants. The purple elephants will count twice. and the red sweaters will count 3 times since red sweaters occurs three times');
$allprases = 'red sweaters, purple elephants'
$phrasearray = explode(',',$allphrases);
foreach ($phrasearray as $k => $phrase) {
$phrase = strtolower(trim($phrase));
echo 'String '.$phrase.' found '.substr_count($string,$phrase).' times.<br />';
}
?>
请注意 substr_count 区分大小写(这就是我在上面的代码中使用 strtolower() 的原因)。这可以很容易地删除,因此上面的代码也区分大小写。