我想将这两个preg_replace合并为一个。例如,如果data-thumb-bg="
替换style="background-image: url('
,则将.jpg
替换为.jpg);
,替换与 $input = preg_replace('#data-thumb-bg="#s', 'style="background-image: url(', $input);
$input = preg_replace('#.jpg#s', '.jpg);', $input); //this must be executed only if a match has been found for above
。
.jpg
我该怎么做?
修改
我想我错误地表达了自己
data-thumb-bg=
只有在 data-thumb-bg
被替换时才应替换。首先替换.jpg
,然后替换data-thumb-bg
按照{{1}}
亲切的问候
答案 0 :(得分:5)
我假设您的最终目标是将元素的属性data-thumb-bg="photo.jpg"
更改为style="background-image: url(photo.jpg);"
。这可以使用capture group和backreference来完成(请注意s
modifier是不必要的,因为我们不使用.
):
$input = preg_replace('/data-thumb-bg="([^"]+)"/', 'style="background-image: url(\1);"', $input);
如果您只想允许.jpg
extensions,可以使用以下表达式:
data-thumb-bg="([^"]+?\.jpg)"
或者,如果您只想允许a handful of image extensions,则可以使用如下表达式:
data-thumb-bg="([^"]+?\.(?:jpe?g|png|gif))"
答案 1 :(得分:2)
您可以将数组传递给preg_replace中的模式和替换参数。
$pattern = array('#data-thumb-bg="#s', '#.jpg#s');
$replace = array('style="background-image: url(', '.jpg);');
$content = preg_replace($pattern, $replace, $input);