Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace a word in a sentence

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

like image 869
Bouki Avatar asked Dec 21 '22 01:12

Bouki


2 Answers

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

/\bStan\b/ig

Will match Stan, but not Stanley.

Demo

like image 122
F.P Avatar answered Dec 24 '22 01:12

F.P


\b means word boundary.

This regex should work:

\bStan\b

RegExr Demo

like image 29
kapa Avatar answered Dec 24 '22 02:12

kapa