2010-05-28 73 views
0

我不确定我怎样才能更好地表达单词的标题,但我的问题是突出显示功能不会突出显示单词末尾的搜索关键字。例如,如果搜索关键词是'self',它会突出显示'self'或'self-lessness'或'Self'[与大写字母S],但不会突出显示'你自己'或'他自己'等。 。突出显示单词末尾的单词

这是亮点功能:

function highlightWords($text, $words) { 
    preg_match_all('~\w+~', $words, $m); 
    if(!$m) 
     return $text; 
    $re = '~\\b(' . implode('|', $m[0]) . ')~i'; 
    $string = preg_replace($re, '<span class="highlight">$0</span>', $text); 

    return $string; 
} 

回答

2

看来你可能有一个\b在您正则表达式,这意味着一个字边界的开始。由于“自己”中的“自我”不是从单词边界开始,因此它不匹配。摆脱\b

+0

你的意思是它应该是'$ re ='〜\('。implode('|',$ m [0])。')〜i';' – input 2010-05-28 20:20:04

+0

是的,据我所知只是看着你的代码。 – Tesserex 2010-05-28 20:34:50

+0

谢谢,它按要求工作。 – input 2010-05-28 20:40:26

0

尝试是这样的:

function highlight($text, $words) { 
    if (!is_array($words)) { 
     $words = preg_split('#\\W+#', $words, -1, PREG_SPLIT_NO_EMPTY); 
    } 
    $regex = '#\\b(\\w*('; 
    $sep = ''; 
    foreach ($words as $word) { 
     $regex .= $sep . preg_quote($word, '#'); 
     $sep = '|'; 
    } 
    $regex .= ')\\w*)\\b#i'; 
    return preg_replace($regex, '<span class="highlight">\\1</span>', $text); 
} 

$text = "isa this is test text"; 
$words = array('is'); 

echo highlight($text, $words); // <span class="highlight">isa</span> <span class="highlight">this</span> <span class="highlight">is</span> test text 

循环,是让每一个搜索词被正确引用...

编辑:修改函数取字符串或数组中$words参数。