Matching EXACT string with preg_replace()?

I have a script that looks similar to this:

$source  = "I am not one of the runners";

$initial  = array("/of/","/runners/");
$replace = array("with","swimmers");

$product = preg_replace($initial, $replace, $source);

This will output:
I am not one with the swimmers.

My problem is, if I had:

$source = "I am not going off the sport";

Then outputted will be:
I am not going withf the sport

As you can see, it doens’t match the full word only, which is what I need it to do.

I rarely use preg_replace(), therefore don’t have huge experience with it.

str_replace() apparently can’t do this, but I know there is an expression to use in preg_replace(), but I can’t figure it out.


Try it with word boundaries:

$source  = "I am not one off the runners";

$initial  = array("/\\bof\\b/","/\\brunners\\b/" );
$replace = array("with","swimmers" );

$product = preg_replace($initial, $replace, $source);


Thanks Chris, that worked muy bien. :wink: