I have a sentence like this :
Stan, Stanley, Stan!
I would like to replace all words "Stan" by Peter to have something like that
Peter, Stanley, Peter!
Here is my issue : Stanley must not be replaced because this is not the word Stan !
Right now I do something like that :
$txt = preg_replace(array('/Stan/i', '/Jack/i'), array('Peter', 'Jennifer'), $txt);
but what I need is a regexp to match only a single word (wich means my word is not immediatly followed by a letter).
I've tried something like this /Stan([^[A-Za-z])/i but this render :
Peter Stanley, Peter
Some punctuation are missing
You can use word boundaries (\b
) for this;
/\bStan\b/ig
Will match Stan
, but not Stanley
.
Demo
\b
means word boundary.
This regex should work:
\bStan\b
RegExr Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With