1

I would like to replace each occurence of hello with bye in a sentence or paragraph.

$sentence = 'nothello hello hello hello hello hello';
$find = 'hello';
$replace = 'bye';
$str = preg_replace('/(^|[\s])'.$find.'([\s]|$)/', '$1'.$replace.'$2', $sentence);

echo $str;

I want this to echo nothello bye bye bye bye bye but instead I get nothello bye hello bye hello bye.

What am I doing wrong?

I can't use \b because I am using lots of languages.

*Edit I guess \b can work if you use the u flag.

twharmon
  • 3,700
  • 3
  • 21
  • 43

3 Answers3

2

This the right place to use zero-length assertions called lookahead and lookbehind instead of matching:

$str = preg_replace('/(?<=^|\s)'.$find.'(?=\s|$)/', $replace, $sentence);
//=> bye bye bye bye bye

More on lookarounds in regex

(?=...) is positive lookahead and (?<=...) is positive lookbehind.

anubhava
  • 713,503
  • 59
  • 514
  • 593
0

You current regex search translate into this:

(^|[\s])hello([\s]|$)

which will match a string start with "hello " -- which match the first hello. or the string " hello " or end with " hello" (a white space before the hello) which will match the 3rd and the last.

if don't need regex search/replace use str_replace as suggested before. If you need to use regex, use a regex test tool/site like https://regex101.com/ to test your regex more closely.

Rabin
  • 684
  • 8
  • 19
0
$sentence = 'nothello hello hello hello hello hello';
$find = 'hello';
$replace = 'bye';
$str = preg_replace('/(^|[\s])'.$find.'([\s]#i|$)/', '$1'.$replace.'$2', $sentence);

echo $str;

you need the "#i" to replace it through the whole string

User__42
  • 130
  • 2
  • 12