2010-10-19 74 views
0

显示文本的问题,我发现对计算器这段代码在Best practices on displaying search results with associated text snippets from actual resultPHP - 大约有搜索词

但是它并不完全做到我想要什么。它显示给定搜索字词周围的文字,但有两个问题

1)我想要整个字只有; 2)它不会限制字符搜索字词,只有之前的那些

下面是代码如下。我如何编辑它来解决这两个问题?在此先感谢:

$text = 'This is an example text page with content. It could be red, green or blue or some other random color. It dont really matter.'; 
$keyword = 'red'; 
$size = 15; // size of snippet either side of keyword 
$snippet = '...'.substr($text, strpos($text, $keyword) - $size, strpos($text, $keyword) + sizeof($keyword) + $size).'...'; 
$snippet = str_replace($keyword, '<strong>'.$keyword.'</strong>', $snippet); 
echo $snippet; 

回答

1
$snippet = preg_replace(
    '/^.*?\s(.{0,'.$size.'})(\b'.$keyword.'\b)(.{0,'.$size.'})\s.*?$/', 
    '...$1<strong>$2</strong>$3...', 
    $text 
); 

这将产生:...It could be <strong>red</strong>, green or blue...。这是\s字符类,它们将之后的15个字符限制为出现的单词分隔符。

+0

感谢您的优雅解决方案 – Steven 2010-10-19 20:40:37