1

我正在为我的网络应用程序创建一个搜索引擎。现在我想突出显示为用户搜索请求找到的结果。我有以下功能:

function highlight($text, $words) {
    foreach ($words as $word) {
            $word = preg_quote($word);              
            $text = preg_replace("/\b($word)\b/i", '<span class="highlighted">\1</span>', $text);               
    }

    return $text;

}

它运行良好,但我不希望整个文本出现在搜索结果页面中,因为它可能是数以千计的文本行,所以我只想显示其中突出显示单词的部分。

4

1 回答 1

1

这个解决方案怎么样?它用于preg_match_all()获取单词的所有出现并在其左侧或右侧显示最多 10 个字符,但仅突出显示匹配的单词

$text = <<<EOF
hello_world sdfsdf
sd fsdfdsf hello_world
 hello_world
safdsa
EOF;

$word = preg_quote('hello_world');
$text = preg_match_all("~\b(.{0,10})($word)(.{0,10})\b~is", $text, $matches);

for($i = 0; $i < count($matches[0]); $i++) {
    echo '<p>'
       . $matches[1][$i]
       . '<span class="hl">'
       . $matches[2][$i]
       . '</span>'
       . $matches[3][$i]
       . '</p>';
}
于 2013-07-02T09:58:11.980 回答