preg_replace() replace only one pattern but match another pattern

438 views Asked by At

I am trying to replace a string with preg_replace()

I want to replace only one pattern 'bbb' but I want to match that pattern and two more ('aaa' and 'ccc') exactly like for example

input                 : 'zzz aaa bbb ccc xxx'
pattern to match      : 'aaa bbb ccc'
output                : 'aaa ccc'

Is it possible to make it happen with just preg_replace() without invoking preg_match()

1

There are 1 answers

0
anubhava On BEST ANSWER

You can use:

echo preg_replace('/.*?(\baaa\b) +\bbbb\b +(\bccc\b).*/', '$1 $2', 'zzz aaa bbb ccc xxx');
//=> aaa ccc