PHP使用特定ID替换<g>标记之间<circle>的每种填充颜色

时间:2017-06-16 09:56:20

标签: php replace tags preg-replace

很抱歉,如果标题不是很好。

我正在使用PHP编写一个脚本,如果它位于具有特定ID的<circle>内,则会更改<g>的填充颜色。

以下是具体的字符串:

<g id="stroke">
<circle cx="6.628mm" cy="23.164mm" r="1.50mm"  fill="#B8BBC0" stroke="#000000" stroke-width="0.282mm"/>
<circle cx="3.920mm" cy="20.170mm" r="1.50mm"  fill="#B8BBC0" stroke="#000000" stroke-width="0.282mm"/>
</g>
<g id="fill" style="visibility: hidden;">
<circle cx="22.593mm" cy="31.429mm" r="1.50mm"  fill="#B8BBC0" stroke="#000000" stroke-width="0.282mm" data-isfill="yes"/>
<circle cx="22.593mm" cy="27.381mm" r="1.50mm"  fill="#B8BBC0" stroke="#000000" stroke-width="0.282mm" data-isfill="yes"/>
</g>

所以,我的想法是:

Change fill="#B8BBC0" to fill="#000000" IF inside <g id="stroke">
Change fill="#B8BBC0" to fill="#FFFFFF" IF inside <g id="fill">

我不确定最好的方法来做到这一点。我知道replace()的基础知识,但我不知道如何编写代码来替换具有特定id的两个标签。谁能帮我写这个?

1 个答案:

答案 0 :(得分:0)

以下是使用DOMDocument

的示例
$data = <<<DATA
<?xml version="1.0"?>
<root>
<g id="stroke">
<circle cx="6.628mm" cy="23.164mm" r="1.50mm"  fill="#B8BBC0" stroke="#000000" stroke-width="0.282mm"/>
<circle cx="3.920mm" cy="20.170mm" r="1.50mm"  fill="#B8BBC0" stroke="#000000" stroke-width="0.282mm"/>
</g>
<g id="fill" style="visibility: hidden;">
<circle cx="22.593mm" cy="31.429mm" r="1.50mm"  fill="#B8BBC0" stroke="#000000" stroke-width="0.282mm" data-isfill="yes"/>
<circle cx="22.593mm" cy="27.381mm" r="1.50mm"  fill="#B8BBC0" stroke="#000000" stroke-width="0.282mm" data-isfill="yes"/>
</g>
</root>
DATA;

$dom = new DOMDocument;
$dom->loadXML($data);
$xpath = new DOMXPath($dom);

$gstrokes = $xpath->query('//g[@id="stroke"]/circle[@fill]'); // Get CIRCLEs (with fill attribute) inside G with ID "stroke"
foreach($gstrokes as $c) {                  // Loop through all CIRCLEs found
   $c->setAttribute('fill', '#000000');     // Set fill="#000000"
}
$gstrokes = $xpath->query('//g[@id="fill"]/circle[@fill]'); // Get CIRCLEs (with fill attribute) inside G with ID "fill"
foreach($gstrokes as $c) {                  // Loop through all CIRCLEs found
   $c->setAttribute('fill', '#FFFFFF');     // Set fill="#000000"
}

echo $dom->saveXML();                       // Save XML

请参阅online PHP demo

结果:

<?xml version="1.0"?>
<root>
<g id="stroke">
<circle cx="6.628mm" cy="23.164mm" r="1.50mm" fill="#000000" stroke="#000000" stroke-width="0.282mm"/>
<circle cx="3.920mm" cy="20.170mm" r="1.50mm" fill="#000000" stroke="#000000" stroke-width="0.282mm"/>
</g>
<g id="fill" style="visibility: hidden;">
<circle cx="22.593mm" cy="31.429mm" r="1.50mm" fill="#FFFFFF" stroke="#000000" stroke-width="0.282mm" data-isfill="yes"/>
<circle cx="22.593mm" cy="27.381mm" r="1.50mm" fill="#FFFFFF" stroke="#000000" stroke-width="0.282mm" data-isfill="yes"/>
</g>
</root>