Reputation: 26095
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
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