Replace a word in a sentence

I have a suggestion like this:

Stan, Stanley, Stan! 

I would like to replace all the words β€œStan” by Peter with something like this

 Peter, Stanley, Peter! 

Here's my problem: Stanley cannot be replaced, because that is not Stan's word!

Now I am doing something like this:

 $txt = preg_replace(array('/Stan/i', '/Jack/i'), array('Peter', 'Jennifer'), $txt); 

but I need the regular expression to match only one word (which means that my word is not immediately followed by a letter).

I tried something like this / Stan ([^ [A-Za-z]) / i, but this render:

 Peter Stanley, Peter 

Some punctuation missing

+4
source share
2 answers

You can use word boundaries ( \b ) for this;

 /\bStan\b/ig 

Will match Stan , but not Stanley .

Demo

+7
source

\b means the word boundary .

This regex should work:

 \bStan\b 

Demo RegExr

+4
source

Source: https://habr.com/ru/post/1399974/


All Articles