I am using following function to highlight searched keywords from string. It's working fine but having little issue.
$text="This is simple test text";
$words="sim text";
echo highlight($text, $words);
Using following function it is highlighting both "simple" & "text" words where I want it should highlight "sim" & "text" words only. What type of changes I need to make to achieve this result. Please advise.
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="SuccessMessage">\1</span>', $text);
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…