仅替换特定元素的 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>

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

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

但要小心,这不是处理大量数据的最佳方法。

试试这个正则表达式:

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

Tested Here - RegEx101

$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);