用中间的通配符替换字符串


Preg_replace string with wildcard in middle

我想替换svg代码字符串中的特定标记。标签看起来像这样:

<rect x="0" fill="#C1984F" width="120" height="80"/>

但是颜色应该换成不同的颜色。。。

我认为它应该这样工作:

$thumbContents = preg_replace('<rect x="0" fill="*" width="120" height="80"/>', '<rect x="0" fill="'.$selectedColor.'" width="120" height="80"/>', $thumbContents);

但是我不知道如何编写正则表达式模式。

如果您坚持使用正则表达式。。。

$tag = '<rect x="0" fill="#C1984F" width="120" height="80"/>';
$newc = 'red';
echo preg_replace('~(<rect[^<>]+?fill=")([^"]+)~', "$1$newc", $tag);

图案表示

(<rect[^<>]+?fill=") - group 1: "<rect" then anything (but not <>) until fill="
([^"]+) - group 2: anything but not a quote (i.e. the color value)

替换:

$1 - whatever has been captured by the group 1
$newc - new color value

你可以试试这个:

<script>
$(document).ready(function(){
    var list = document.getElementsByTagName("rect")[0];
    alert(list.getAttribute('fill'));// change the value here
});
</script>
<rect x="0" fill="#C1984F" width="120" height="80"/>

抱歉,它是用javascript编写的。