仅将 XML/SVG 元素属性替换为特定元素


replace xml/svg element attribute for specific element only

我有这样的'XML',

<text>
    <tspan fill='rgba(0,0,0,0)'>abc</tspan>
</text>
<rect fill='rgba(0,0,0,0)'></rect>

我正在尝试用rgb(替换rgba(,但它替换数据中发生的所有实例。我只想替换tspan标签的所有实例。我尝试str_replace但将所有实例替换为数据。

输出应如下所示

<text>
    <tspan fill='rgb(0,0,0,0)'>abc</tspan>
</text>
<rect fill='rgba(0,0,0,0)'></rect>

试试这个正则表达式:

rgba(?=(.*)<'/tspan>)

在这里测试 - 正则表达式101

$re = "/rgba(?=(.*)<''/tspan>)/"; 
$str = "<text><tspan stroke='' opacity='' fill='rgba(0,0,0,0)'>abc</tspan><tspan fill='rgba(0,0,0,0)'><h1>anything</h1></tspan></text><rect fill='rgba(0,0,0,0)'></rect>"; 
$subst = "rgb"; 
$result = preg_replace($re, $subst, $str);

您仍然可以使用str_replace,但使用更长的字符串作为"find"参数:

str_replace("<tspan fill='rgba(0,0,0,0)", "<tspan fill='rgb(0,0,0,0)", $your_string);

但要小心,这不是对大量数据执行此操作的最佳方法。