2013-07-02 137 views
1

我正在为我的Web应用程序创建搜索引擎。现在我想突出显示用户搜索请求的结果。我有以下功能:在php中突出显示单词并返回包含突出显示的单词的部分

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; 

}

它运作良好,但我不希望整个文本显示在搜索结果页面,因为它可以是文本的行thounds,所以我只想显示突出显示单词的部分内容。

回答

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>'; 
} 
+0

? – Jamol

+0

检查我的更新 – hek2mgl

+0

他想限制文本,而不是取代某些东西?这个函数如何防止文本长达数千个符号? – leuchtdiode