PSD to HTML conversion PSD to HTML conversion PSD2HTML.com with over 300 professionals takes the designs to HTML and beyond

Code Snippet

Home » Code Snippets » PHP » Highlight a Substring

Highlight a Substring

<?php
       $text='Would you be so kind to highlight css-tricks.com in this string?';
       $search='css-tricks.com';

       echo textHighlight($text,$search);

       //Performs a regex-texthighlight
       function textHighlight($text,$search,$highlightColor='#0000FF',$casesensitive=false)
       {
               $modifier=($casesensitive) ? 'i' : '';
               //quote search-string, cause preg_replace wouldn't work correctly if chars like $?. were in search-string
               $quotedSearch=preg_quote($search,'/');
               //generate regex-search-pattern
               $checkPattern='/'.$quotedSearch.'/'.$modifier;
               //generate regex-replace-pattern
               $strReplacement='$0';
               return preg_replace($checkPattern,$strReplacement,$text);
       }
?>

This code performs a regular-expression-replace to add a span-tag with a definable color. Can be used either for case-sensitive and case-insensitive replacements.

Subscribe to The Thread

  1. feha says:

    This will not work …
    you are not using the : $highlightColor

    anywhere within replace code …

    regards
    feha

  2. pandaboy says:

    @feha, it maybe too late for you to see this, but I found this in the php_manual on preg_replace in the comments – simpler and works fine for most cases:


    function highlight($haystack,$needle)
    {
    $haystack=preg_replace("/($needle)/i","<span style='font-weight:bold'>\${1}</span>",$haystack);
    return $haystack;
    }

Speak, my friend

At this moment, you have an awesome opportunity* to be the person your mother always wanted you to be: kind, helpful, and smart. Do that, and we'll give you a big ol' gold star for the day (literally).

Posting tips:
  • You can use basic HTML
  • When posting code, please turn all
    < characters into &lt;
  • If the code is multi-line, use
    <pre><code></code></pre>
Thank you,
~ The Management ~