我将格式良好的xml文档转换为字符串变量.我想使用preg_replace为每个xml标记添加一个已定义的属性.
例如替换:
<tag1>
<tag2> some text </tag2>
</tag1>
Run Code Online (Sandbox Code Playgroud)
通过:
<tag1 attr="myAttr">
<tag2 attr="myAttr"> some text </tag2>
</tag1>
Run Code Online (Sandbox Code Playgroud)
所以我基本上需要正则表达式来查找任何开始标记并添加我的属性,但我是一个完整的正则表达式菜鸟.
sou*_*rge 13
不要使用正则表达式来处理xml.Xml不是常规语言.使用php的xml扩展名代替:
$xml = new SimpleXml(file_get_contents($xmlFile));
function process_recursive($xmlNode) {
$xmlNode->addAttribute('attr', 'myAttr');
foreach ($xmlNode->children() as $childNode) {
process_recursive($childNode);
}
}
process_recursive($xml);
echo $xml->asXML();
Run Code Online (Sandbox Code Playgroud)
所有包含正则表达式的答案都会破坏这个有效的xml,例如:
<?xml version="1.0" encoding='UTF-8'?>
<html>
<head>
<!-- <meta> ... </meta> -->
<script>//<![CDATA[
function load() {document.write('<tt>Test</tt>');}
//]]></script>
<title><![CDATA[Fancy <<SiteName>> [with Breadcrumbs] > in > title]]></title>
</head>
<body onload="load()">
<input
type="submit"
value="multiline
button
text"
/>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)