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";

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

3 回答 3

3

你可以得到所有的句子。

试试这个:

$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);
于 2012-09-02T21:06:39.993 回答
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;
});
于 2012-09-02T21:14:38.023 回答
1

由于你用 反转字符串strrev(),你会发现[space].而不是.[space]

于 2012-09-02T21:06:45.720 回答