首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >搜索模式频率

搜索模式频率
EN

Stack Overflow用户
提问于 2011-12-07 00:54:40
回答 3查看 143关注 0票数 0

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

给出一个文本blob

“这是我想找的红色毛衣和紫色大象的超级字符串。紫色的大象会数两次。红色毛衣会数三次,因为红色毛衣会出现三次。”

和一个短语列表

“红色的毛衣,紫色的大象”

我想搜索文本blob并返回出现次数

因此

红色毛衣=3,紫色大象=2

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2011-12-07 00:58:36

http://www.php.net/manual/en/function.substr-count.php

代码语言:javascript
复制
$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));
}
票数 4
EN

Stack Overflow用户

发布于 2011-12-07 01:05:38

您可以使用substr_count来搜索文本中的字符串。只需注意,在您的示例中,如果文本是“棕色毛衣”,则“红色毛衣”将计入+1。

您也可以使用regular expressions。就像preg_match("/$string/",$text);一样。这将返回找到该字符串的次数。

此外,如果您想搜索几个以逗号分隔的字符串(如您的示例),您首先需要拆分字符串。您可以使用explode来实现这一点。$strings = explode(",",$search);

票数 2
EN

Stack Overflow用户

发布于 2011-12-07 01:03:38

像这样的东西应该是有效的:

代码语言:javascript
复制
<?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())。这可以很容易地删除,以便上面的代码也区分大小写。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8403683

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档