The Lodge is members-only design/dev videos and Office Hours.

Next Office Hours Session: "Implementing an SVG Icon System" Nov 30 - 6:00 PM Eastern

Highlight a Substring

Last updated on:
       $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.


  1. feha
    Permalink to comment#

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

    anywhere within replace code …


  2. pandaboy
    Permalink to comment#

    @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;

Leave a Comment

Posting Code

We highly encourage you to post problematic HTML/CSS/JavaScript over on CodePen and include the link in your post. It's much easier to see, understand, and help with when you do that.

Markdown is supported, so you can write inline code like `<div>this</div>` or multiline blocks of code in in triple backtick fences like this:

  function example() {
    element.innerHTML = "<div>code</div>";

There's a whole bunch of content on CSS-Tricks.

Search for Stuff   •   Browse the Archives

Get the Newsletter ... or get the RSS feed