我将格式良好的 xml 文档转换为字符串变量。我想使用 preg_replace 为每个 xml 标签添加定义的属性。
例如替换:
<tag1>
<tag2> some text </tag2>
</tag1>
通过:
<tag1 attr="myAttr">
<tag2 attr="myAttr"> some text </tag2>
</tag1>
所以我基本上需要正则表达式来查找任何开始标记并添加我的属性,但我是一个完整的正则表达式菜鸟。
最佳答案
不要使用正则表达式来处理 xml。 Xml 不是常规语言。使用 xml extensions of php相反:
$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();
所有包含正则表达式的答案都会破坏这个有效的 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>
关于php - 在任何 xml 标签中添加属性的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1357357/