Skip to main content
Home / Code Snippets / PHP / Highlight a Substring
       $text='Would you be so kind to highlight in this string?';

       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
               //generate regex-search-pattern
               //generate regex-replace-pattern
               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.