PHP using preg_replace to highlight string that is part of a word

214 views Asked by At

So I have the following code which highlights the word/s which were entered into a search bar in search results:

$sk = explode(" ",$searchVal); 
    foreach ($searchPostResults as $pagePosts)
        echo '<li><span class="searchResult"><a href="' 
        . get_the_permalink($pagePosts->ID) . '" title="">' . 
        preg_replace('/\b(' . implode('|', $sk) . ')\b/iu', 
                     '<strong class="searchHighlight">\0</strong>', 
                     get_the_title($pagePosts->ID)) 
         . '</a></span></li>';

Now it works for the most part. Lets say I enter the search term "how to" in the search bar, the word how is highlighted. Now if the word how is inside another word like shower, I would like to highlight how like so:

s<strong class="searchHighlight">how</strong>er

Anyone know how I might adjust the code to do this.

Cheers

1

There are 1 answers

4
chris85 On BEST ANSWER

The behavior you are describing is the opposite of most peoples intentions, and probably why your regex has the \b in it. The \b is a word boundary and makes it so you can have only full word matches. Remove the \bs and it should work. You also won't need the capture group.

preg_replace('/' . implode('|', $sk) . '/iu',