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.
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.