Created
February 2, 2014 19:44
-
-
Save grandmanitou/8773691 to your computer and use it in GitHub Desktop.
PHP highlight words in text using regex
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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