【问题标题】:Get sentence(s) which include(s) searched word(s)?获取包含搜索词的句子?
【发布时间】:2012-09-02 21:01:09
【问题描述】:

我想获得包含搜索词的句子。我已经尝试过了,但无法使其正常工作。

$string = "I think instead of trying to find sentences, I'd think about the amount of 
context around the search term I would need in words. Then go backwards some fraction of this number of words (or to the beginning) and forward the remaining number 
of words to select the rest of the context.";

$searchlocation = "fraction";

$offset = stripos( strrev(substr($string, $searchlocation)), '. ');
$startloc = $searchlocation - $offset;
echo $startloc;

【问题讨论】:

    标签: php get


    【解决方案1】:

    你可以得到所有的句子。

    试试这个:

    $string = "I think instead of trying to find sentences, I'd think about the amount of 
    context around the search term I would need in words. Then go backwards some fraction of this number of words (or to the beginning) and forward the remaining number 
    of words to select the rest of the context.";
    
    $searchlocation = "fraction";
    
    $sentences = explode('.', $string);
    $matched = array();
    foreach($sentences as $sentence){
        $offset = stripos($sentence, $searchlocation);
        if($offset){ $matched[] = $sentence; }
    }
    var_export($matched);
    

    【讨论】:

      【解决方案2】:

      使用array_filter函数

      $sentences = explode('.', $string);
      $result = array_filter(
          $sentences, 
          create_function('$x', "return strpos(\$x, '$searchlocation');"));
      

      注意:create_function的第二个参数中的双引号是必须的。

      如果你有匿名函数支持,可以使用这个,

      $result = array_filter($sentences, function($x) use($searchlocation){
              return strpos($x, $searchlocation)!==false;
      });
      

      【讨论】:

        【解决方案3】:

        由于您使用strrev() 反转字符串,您将找到[space]. 而不是.[space]

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-04-08
          • 2016-02-16
          • 1970-01-01
          相关资源
          最近更新 更多