Skip to content

Instantly share code, notes, and snippets.

@grandmanitou
Created February 2, 2014 19:44
Show Gist options
  • Save grandmanitou/8773691 to your computer and use it in GitHub Desktop.
Save grandmanitou/8773691 to your computer and use it in GitHub Desktop.
PHP highlight words in text using regex
function highlight($text, $words) {
preg_match_all('~\w+~', $words, $m);
if(!$m)
return $text;
$re = '~\\b(' . implode('|', $m[0]) . ')\\b~';
return preg_replace($re, '<b>$0</b>', $text);
}
$text = '
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat.
';
$words = 'ipsum labore';
print highlight($text, $words);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment