highlighting words at the end of a word
i'm not sure how i could have phrased the title better, but my issue is that the highlight function doesn't highlight the search keywords which are at the end of the word. for example, if the search keyword is 'self', it will highlight 'self' or 'self-lessness' or 'Self' [with capital S] but it will not highlight the self of 'yourself' or 'himself' etc. .
this is the highlight function:
开发者_Go百科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;
}
It seems you might have a \b
at the beginning of your regex, which means a word boundary. Since the 'self' in 'yourself' doesn't start at a word boundary, it doesn't match. Get rid of the \b
.
Try something like this:
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
The loop, is so that every search word is properly quoted...
EDIT: Modified function to take either string or array in $words
parameter.
精彩评论