I created a function that selects individual words inside a string. It looks like this:
function highlight($input, $keywords) { preg_match_all('~[\w\'"-]+~', $keywords, $match); if(!$match) { return $input; } $result = '~\\b(' . implode('|', $match[0]) . ')\\b~i'; return preg_replace($result, '<strong>$0</strong>', $input); }
I need a function to work with an array of different words that support a space in the search.
Example:
$search = array("this needs", "here", "can high-light the text");
$string = "This needs to be in here so that the search variable can high-light the text";
echo highlight($string, $search);
Here is what I have been fixing so far to work as I need it:
function highlight($input, $keywords) { foreach($keywords as $keyword) { preg_match_all('~[\w\'"-]+~', $keyword, $match); if(!$match) { return $input; } $result = '~\\b(' . implode('|', $match[0]) . ')\\b~i'; $output .= preg_replace($result, '<strong>$0</strong>', $keyword); } return $output; }
Obviously, this does not work, and I'm not sure how to make it work (regular expression is not my forte).
Another issue that could be a problem, how will a function deal with multiple matches? For example, $search = array("in here", "here so"); the result will be something like:
This needs to be <strong>in <strong>here</strong> so</strong> that the search variable can high-light the text
But it should be:
This needs to be <strong>in here so</strong> that the search variable can high-light the text