我有一个config.ini文件,格式为XML,如下所示:
<positions>
<position>
<name>BLOCK TAB 1</name>
<tag>[BLOCK_TAB_1]</tag>
</position>
<position>
<name>PERSONALAREA</name>
<tag>[PERSONALAREA]</tag>
</position>
</positions>
我试图删除块:
<position>
<name>BLOCK TAB 1</name>
<tag>[BLOCK_TAB_1]</tag>
</position>
通过使用preg_replace
$find1 = "/<name>BLOCK TAB 1<'/name>/";
$find2 = "/<tag>'[BLOCK_TAB_1']<'/tag>/";
$contents = preg_replace($find1, "", $contents);
$contents = preg_replace($find2, "", $contents);
但内容将是
<positions>
<position>
</position>
<position>
<name>PERSONALAREA</name>
<tag>[PERSONALAREA]</tag>
</position>
</positions>
空的<position>
标签(里面有标签)仍然在这里。
尝试使用/<position[^>]*><''/position[^>]*>/
来替换空的<position>
标记,但由于里面有制表符,所以替换不起作用。
有人有主意吗?
您不应该使用regex来解析此XML。在本例中,您可以使用XPath轻松识别具有文本"BLOCK TAB 1"的<name>
,然后选择其父级并将其删除:
$doc = new DOMDocument;
$doc->loadXML($xml);
$xpath = new DOMXpath($doc);
$positions = $xpath->query('//name[text()="BLOCK TAB 1"]/parent::position');
foreach ($positions as $position) {
// Remove it
$position->parentNode->removeChild($position);
}
echo $doc->saveXML();
示例