DOMElement替换HTML值 [英] DOMElement replace HTML value
问题描述
我在DOMElement
中有这个HTML字符串:
I have this HTML string in a DOMElement
:
<h1>Home</h1>
test{{test}}
我想以仅
<h1>Home</h1>
test
仍然存在(所以我想删除{{test}}
).
remains (so I want to remove the {{test}}
).
此刻,我的代码如下:
$node->nodeValue = preg_replace(
'/(?<replaceable>{{([a-z0-9_]+)}})/mi', '' , $node->nodeValue);
这不起作用,因为nodeValue
不包含节点的HTML值.
除了使用$node->C14N()
之外,我不知道如何获取节点的HTML字符串,但是通过使用C14N
,我无法替换内容.
有什么想法可以删除这样的HTML字符串中的{{test}}
吗?
This doesn't work because nodeValue
doesn't contain the HTML value of the node.
I can't figure out how to get the HTML string of the node other than using $node->C14N()
, but by using C14N
I can't replace the content.
Any ideas how I can remove the {{test}}
in an HTML string like this?
推荐答案
您是否尝试过DOMDocument::saveXML
函数? ( http://php.net/manual/en/domdocument.savexml.php)
Have you tried the DOMDocument::saveXML
function? (http://php.net/manual/en/domdocument.savexml.php)
它有第二个参数$node
,您可以用它指定要打印HTML/XML的节点.
It has a second argument $node
with which you can specify which node to print the HTML/XML of.
例如,
<?php
$doc = new DOMDocument('1.0');
// we want a nice output
$doc->formatOutput = true;
$root = $doc->createElement('body');
$root = $doc->appendChild($root);
$title = $doc->createElement('h1', 'Home');
$root->appendChild($title);
$text = $doc->createTextNode('test{{test}}');
$text = $root->appendChild($text);
echo $doc->saveXML($root);
?>
这将为您提供:
<body>
<h1>Home</h1>
test{{test}}
</body>
如果您不希望使用<body>
标签,则可以遍历其所有子节点:
If you do not want the <body>
tag, you could cycle through all of its childnodes:
<?php
foreach($root->childNodes as $child){
echo $doc->saveXML($child);
}
?>
这将为您提供:
<h1>Home</h1>test{{test}}
您当然可以用已经使用的正则表达式替换{{test}}
:
you can then of course replace {{test}}
by the regex that you are already using:
<?php
$xml = '';
foreach($root->childNodes as $child){
$xml .= preg_replace(
'/(?<replaceable>{{([a-z0-9_]+)}})/mi', '',
$doc->saveXML($child)
);
}
?>
这将为您提供:
<h1>Home</h1>test
注意:我尚未测试代码,但这应该可以为您提供总体思路.
Note: I haven't tested the code, but this should give you the general idea.
这篇关于DOMElement替换HTML值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!