Friendly Code Friendly Code - 8 days ago 4
PHP Question

How to replace full words that are either fully or part matched

I am trying to use either preg_replace or str_ireplace to wrap a span class tag around the keyword found, however with str_ireplace it will cut a word such as 'wooding' in half eg:

<span class="highlight">wood</span>ing


Here's an example of needle, haystack and required return:

Needle:

wood


Haystack:

wood and stuff
this doesnt contain the keyword
Wooding is what we do


What I would like returned:

<span class="highlight">wood</span> and stuff
this doesnt contain the keyword
<span class="highlight">Wooding</span> is what we do


Here's a link to my preg_replace experimentation:
http://www.phpliveregex.com/p/i4m

Answer

Try this regex: \b(wood.*?)\b, it matches a word beginning with wood followed by any number of word characters.

$intput = 'put your input here';
$result = preg_replace(/\b(wood.*?)\b/i, '<span class="highlight">\\1</span>', $input);