preg_replace how to replace only matching xxx($1)y

2019-01-31 21:21发布

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?

4条回答
做个烂人
2楼-- · 2019-01-31 22:07

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.

查看更多
淡お忘
3楼-- · 2019-01-31 22:10

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

查看更多
Animai°情兽
4楼-- · 2019-01-31 22:15

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);
查看更多
Luminary・发光体
5楼-- · 2019-01-31 22:18

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.

查看更多
登录 后发表回答