查找段落

时间:2015-06-19 08:39:00

标签: php regex algorithm compare pattern-matching

我有一个段落,我必须解析不同的关键字。例如,段落:

“我想改变世界。想让它成为一个更好的生活场所。和平,爱与和谐。生活就是一切。我们可以让我们的世界一个好的地方生活“

我的关键字是

“世界”,“地球”,“地方”

我应该在每次比赛时报告多少次。

输出应为:

“世界”2次,“地点”1次

目前,我只是将Paragraph字符串转换为字符数组,然后将每个关键字与所有数组内容进行匹配。 这是在浪费我的资源。 请指导我一个有效的方法。(我使用的是PHP)

3 个答案:

答案 0 :(得分:1)

<?php
    Function woohoo($terms, $para) {
     $result =""; 
     foreach ($terms as $keyword) {
        $cnt = substr_count($para, $keyword);
        if ($cnt) {
          $result .= $keyword. " found ".$cnt." times<br>";
        }
      }
      return $result;
    }
    $terms = array('world', 'earth', 'place');
    $para = "I want to make a change in the world. Want to make it a better place to live.";
    $r = woohoo($terms, $para);
    echo($r);
?>

答案 1 :(得分:1)

正如@CasimiretHippolyte评论的那样,正则表达式是更好的方法,因为可以使用word boundaries。使用i flag可以进一步进行无壳匹配。与preg_match_all返回值一起使用:

  

返回完整模式匹配的数量(可能为零),如果发生错误则返回FALSE。

匹配一个单词的模式是:/\bword\b/i。生成一个数组,其中键是来自搜索$words的单词值,值是映射的单词计数,preg_match_all返回:

$words = array("earth", "world", "place", "foo");

$str = "at Earth Hour the world-lights go out and make every place on the world dark";

$res = array_combine($words, array_map( function($w) USE (&$str) { return
       preg_match_all('/\b'.preg_quote($w,'/').'\b/i', $str); }, $words));

print_r($res); test at eval.in 输出到:

  

阵   (       [earth] =&gt; 1       [world] =&gt; 2       [place] =&gt; 1       [foo] =&gt; 0   )

使用preg_quote来逃避不必要的字词,如果你知道的话,它们不包含任何特价。对于使用array_combine 的内联匿名函数,需要PHP 5.3

答案 2 :(得分:0)

我将使用preg_match_all()。以下是代码中的外观。实际函数返回找到的项目数,但$ matches数组将保存结果:

<?php
$string = "world";

$paragraph = "I want to make a change in the world. Want to make it a better place to live. Peace, Love and Harmony. It is all life is all about. We can make our world a good place to live";

if (preg_match_all($string, $paragraph, &$matches)) {
  echo 'world'.count($matches[0]) . "times";
}else {
  echo "match NOT found";
}
?>
相关问题