Monday 23 February 2015

PHP: Highlight specific words in a phrase

Sometimes, for example, when displaying search results, it is a great idea to highlight specific words. This is exactly what the following function can do:

<?php

function highlight($sString, $aWords) {

 if (!is_array ($aWords) || empty ($aWords) || !is_string ($sString)) {
  return false;
 }

 $sWords = implode ('|', $aWords);
  return preg_replace ('@\b('.$sWords.')\b@si', '<strong style="background-color:yellow">$1</strong>', $sString);
}
?>

0 comments:

Post a Comment