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

PartySoft picture PartySoft · Feb 4, 2011 · Viewed 34.6k times · Source

I'm trying to use a regular expression to erase only the matching part of an string. I'm using the preg_replace function and have tried to delete the matching text by putting parentheses around the matching portion. Example:

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

This replaces the entire string with '' though. I only want to erase text2, but leave text1 and text3 intact. How can I match and replace just the part of the string that matches?

Answer

mario picture mario · Feb 4, 2011

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.