<?php
// The class. Normally this would be in its own file and included using include_once or require_once
class StringHighlighter {
public static function HighlightWords($string, $words) {
if(!is_array($words) || empty($words) || !is_string($string))
return false;
$swords = implode('|',$words);
return preg_replace('@\b('.$swords.')\b@si', '<strong style="background-color:yellow;">$1</strong>', $string);
}
}
// Hardcoded words and paragraph, normally this would come from a database I would expect
$words_to_highlight = array('code','php');
$paragraph = 'This is a very simple php script which highlights words in a string when called. You could use this code to highlight words in search results.';
// Output the string with the specified words highlighted.
echo StringHighlighter::HighlightWords($paragraph, $words_to_highlight);
?>