Highlight specific words in a phrase with PHP


/ Published in: PHP
Save to your folder(s)

You may use this code to highlight specific words in your displaying search results.


Copy this code and paste it in your HTML
  1. <?php
  2. function highlight($str, $words){
  3. if(!is_array($words) || empty($words) || !is_string($str)){
  4. return false;
  5. }
  6. $arr_words = implode('|', $words);
  7. return preg_replace(
  8. '@\b('.$arr_words.')\b@si',
  9. '<strong style="background-color:yellow">$1</strong>',
  10. $str
  11. );
  12. }
  13. ?>

URL: http://www.apphp.com/index.php?snippet=php-highlight-specific-words-in-a-phrase

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.