Highlight specific words in a phrase

  • Language:: PHP
  • Type:: Back-end
  • Context:: create your own multi-select categories to further describe the purpose of the snippet e.g. is this to do with styling, making API calls, creating utility functions etc.
  • Description – a text-based description of the snippet

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:

`1.``function`  `highlight(``$sString``, ``$aWords``) {`
 
`2.``if`  `(!``is_array`  `(``$aWords``) || ``empty`  `(``$aWords``) || !``is_string`  `(``$sString``)) {`
 
`3.``return`  `false;`
`4.``}`
`5.`
`6.``$sWords`  `= implode (``'|'``, ``$aWords``);`
 
`7.``return`  `preg_replace (``'@\b('``.``$sWords``.``')\b@si'``, ``'<strong style="background-color:yellow">$1</strong>'``, ``$sString``);`
 
`8.``}`

Source: http://www.phpsnippets.info/highlights-words-in-a-phrase

  • Dependencies::

📇Additional Metadata