0
$text_string = "One One One,One.One OneTwo, Onetwo .Onetwo TwoOne One";

I want to replace the word "One" with "Three" which is alone or between special characters or at the beginning/ending of the string. Have anybody an idea?

The result must be:

$text_string = "Three Three Three,Three.Three OneTwo, Onetwo .Onetwo TwoOne Three";
Em Hi
  • 59
  • 6

1 Answers1

2

You can use \b to check for word boundaries:

$str = 'One One One,One.One OneTwo, Onetwo .Onetwo';
$replaced = preg_replace('/\bOne\b/', 'Three', $str);
echo $replaced; // Three Three Three,Three.Three OneTwo, Onetwo .Onetwo TwoOne Three
mrks
  • 8,033
  • 1
  • 33
  • 62