44

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?

ekad
  • 14,436
  • 26
  • 44
  • 46
PartySoft
  • 2,749
  • 7
  • 39
  • 55

4 Answers4

58

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);
Mansoor Siddiqui
  • 20,853
  • 10
  • 48
  • 67
49

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.

mario
  • 144,265
  • 20
  • 237
  • 291
17

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.

aorcsik
  • 15,271
  • 5
  • 39
  • 49
  • 6
    Please use $n instead of \\n. – NikiC Feb 04 '11 at 13:03
  • @NikiC is it only style or you have some reason behind it? – aorcsik Jan 29 '14 at 19:51
  • 5
    Use of $n over \\n is the official recommendation, quoting the manual: "[...] may contain references of the form \\n or (since PHP 4.0.4) $n, with the latter form being the preferred one". I don't know the exact reasoning behind this, but the $ syntax is at least a) more readable and b) has support for ${n} as well. Maybe there are additional reasons. – NikiC Jan 29 '14 at 23:26
  • @NikiC so it is indeed a recommendation, I'll keep it in mind, thanks! It's hard to leave behind old habits. – aorcsik Jan 30 '14 at 11:04
  • 5
    Better use this in 2018: http://dk2.php.net/manual/en/function.preg-replace-callback.php – Andreas Riedmüller Feb 02 '18 at 12:35
-5

The simplest way has been mentioned several types. Another idea is lookahead/lookback, they're overkill this time but often quite useful.

abesto
  • 2,331
  • 16
  • 28