Leo Jiang
Leo Jiang

Reputation: 26095

PHP preg_replace: How can I match something but not replace it?

For example, if I wanted to preg_replace the title of a HTML element:

$str = preg_replace('/title=\"([^\"]+)\"/', 'foo', $str);

Please do not give me other solutions (non regex) for this specific example, this is merely an example. I need a solution that works for any regular expressions.

Upvotes: 3

Views: 446

Answers (1)

mario
mario

Reputation: 145482

If you want to match parts with preg_replace, but only partially replace something else, then there are two options.
Either you just reinsert the matched parts (enclose in capture groups, and then use $1 and $3):

 $str = preg_replace('/(title=")([^"]+)(")/', '$1foo$3', $str);

Or you use assertions:

 $str = preg_replace('/(?<=title=")([^"]+)(?=")/', 'foo', $str);

Upvotes: 7

Related Questions