Friendly Code Friendly Code - 1 year ago 74
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:




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:

Answer Source

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download