preg_replace how to replace only matching xxx($1)yyy pattern inside the selector preg_replace how to replace only matching xxx($1)yyy pattern inside the selector php php

preg_replace how to replace only matching xxx($1)yyy pattern inside the selector


Use backreferences (i.e. brackets) to keep only the parts of the expression that you want to remember. You can recall the contents in the replacement string by using $1, $2, etc.:

preg_replace('/(text1)text2(text3)/is','$1$2',$html);


There is an alternative to using text1 and text3 in the match pattern and then putting them back in via the replacement string. You can use assertions like this:

preg_replace('/(?<=text1)(text2)(?=text3)/', "", $txt);

This way the regular expression looks just for the presence, but does not take the two strings into account when applying the replacement.

http://www.regular-expressions.info/lookaround.html for more information.


Try this:

$text = preg_replace("'(text1)text2(text3)'is", "$1$2", $text);

Hope it works!

Edit: changed \\1\\2 to $1$2 which is the recommended way.