Php preg_match alternative (finding keyword and surrounding words in a string)

I’m trying to find a keyword (ex. “dog bone”) in a paragraph string (ex. “I bought my lucky dog a new dog bone and he loves it.” using PHP preg_match & preg_replace. I found some code (from early 2000s) that works ok but is slow.

Anyone know of a good alternative or better way to write this code?


$tmp = "dog bone"
$string = "I bought my lucky dog a new dog bone and he loves it."

preg_match("/(\\w+)? ?(\\w+)? ?(\\w+)? ?(\\w+)? ?(\\w+)? ?$tmp? ?(\\w+)? ?(\\w+)? ?(\\w+)? ?(\\w+)? ?(\\w+)?/i", $string, $result);

if ($result[0] != "") {
$my_output = preg_replace("/$tmp/i","<B>$tmp</B>",$result[0]);
}

echo $my_output;

I found a way to speed up the process (though the code is much longer).

It has to do with breaking up the string by word into an array then doing an array search for the keyword(s).

It takes too long to explain but this page helped me out a lot.
http://stackoverflow.com/questions/4314503/any-faster-simpler-alternative-to-php-preg-match

That regexp pattern seems awfully convoluted. This should be all you need.

$my_output = preg_replace(“/($tmp)/i”, “<b>$1</b>”, $string);

In fact, you may not need a regexp at all.

$my_output = str_replace($tmp, “<b>$tmp</b>”, $string);