搜索模式频率


Search Pattern Frequency

最好是PHP解决方案-但任何想法都很棒。

给出一个文本blob

'这是一个包含一些内容的超级字符串,我想找到红色毛衣和紫色大象。紫色大象算两次。红色毛衣会出现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);。这将返回字符串被找到的次数。

同样,如果您想搜索由逗号分隔的多个字符串(如您的示例),您首先需要拆分字符串。你可以用explosion。$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()的原因)。这可以很容易地删除,这样上面的代码也是区分大小写的。