PHP Stringhighlighter


SUBMITTED BY: Guest

DATE: July 4, 2013, 8:04 a.m.

FORMAT: PHP

SIZE: 957 Bytes

HITS: 839

  1. <?php
  2. // The class. Normally this would be in its own file and included using include_once or require_once
  3. class StringHighlighter {
  4. public static function HighlightWords($string, $words) {
  5. if(!is_array($words) || empty($words) || !is_string($string))
  6. return false;
  7. $swords = implode('|',$words);
  8. return preg_replace('@\b('.$swords.')\b@si', '<strong style="background-color:yellow;">$1</strong>', $string);
  9. }
  10. }
  11. // Hardcoded words and paragraph, normally this would come from a database I would expect
  12. $words_to_highlight = array('code','php');
  13. $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.';
  14. // Output the string with the specified words highlighted.
  15. echo StringHighlighter::HighlightWords($paragraph, $words_to_highlight);
  16. ?>

comments powered by Disqus