PHP Text Highlighter

This snippet accepts an array of words, and a descriptive name which can be used to reference the words, like so:


$this->scan(array('mysql','css','js','content management system',
  'xhtml','xml','rss','html','lamp','ria',
  'sugar','php','zend framework','oo','dojo',
  'doctrine','javascript','smarty','ez publish'),'skills');

It scans a block of text, and returns matches enclosed in span tags, which can be highlighted using CSS.


private function scan($aWords,$sType)
{
  // Thanks to: http://us.php.net/manual/en/function.array-walk.php#103056
  array_walk($aWords, create_function('&$val', '$val = \'/(\W)(\'.$val.\')\W)/umi\';'));
  $this->data[$sType.'_HTML']=preg_replace($aWords,'\1<span class="found">\2</span>\3',
    $this->data['sContent'],1,$this->data[$sType.'_COUNT']);
}

// Used to access the private $data array 
public function __get($sName)
{
  if(isset($this->data[$sName]))
    return $this->data[$sName];
  else
    return null;
}

To extract the HTML and a count of the matches:


$sOutput=<<<BLOCK
<div id="skills_check">
$oResponse->skills_HTML
<div id="skills_count">
  Skills matched: $oResponse->skills_COUNT
</div>
BLOCK;

A match is considered a string with non-word characters immediately before and after. This makes mismatches less likely. For example, ‘oo’ would not match ‘Joomla’, but it would match ‘ oo.’, or ‘,oo and …’.

There can be several scans in a page, using the id of a parent div can allow them to be presented differently, for example:

span.found
{
font-weight:bolder;
}
#skills_check span.found
{
color:#22ff22;
}