我正在使用这个例程:
$dom = new DomDocument();
@$dom->loadHTML('<?xml encoding="UTF-8">' . $row['body']);
$xpath = new DOMXPath($dom);
$as = $dom->getElementsBytagName('a');
//if anchor exists
if($as->length)
{
foreach ($as as $a)
{
//get parrent af anchor
$a_parent = $a->parentNode;
//create h4 element
$h4 = $dom->createElement('h4');
//append a to h4
$h4->appendChild($a);
//append h4 to anchor parent
$a_parent->appendChild($h4);
}
$body = $dom->saveHTML();要查找html字符串中的所有a标记,请执行以下操作:
<p>Lorem Ipsum is simply dummy text of the printing and
typesetting<a href="#">foo</a> industry.</p>并用h4标签包装a标签。当我执行myscript时,结果是错误的,输出是:
<p>Lorem Ipsum is simply dummy text of the printing and
typesetting industry.<h4><a href="#">foo</a></h4></p>但我想要这样的格式:
<p>Lorem Ipsum is simply dummy text of the printing
and typesetting<h4><a href="#">foo</a></h4> industry.</p>有什么建议请提出来。
发布于 2012-03-11 21:58:29
您是否尝试过使用replaceChild()?在这里,您的代码被修改了。无法尝试,但应该可以工作。
$dom = new DomDocument();
@$dom->loadHTML('<?xml encoding="UTF-8">' . $row['body']);
$xpath = new DOMXPath($dom);
$as = $dom->getElementsBytagName('a');
//if anchor exists
if($as->length)
{
foreach ($as as $a)
{
//get parrent af anchor
$a_parent = $a->parentNode;
//create h4 element
$h4 = $dom->createElement('h4');
//append a to h4
$clone = $a->cloneNode();
$h4->appendChild($clone);
//append h4 to anchor parent
$a_parent->replaceChild($h4, $a);
}
$body = $dom->saveHTML();https://stackoverflow.com/questions/9655355
复制相似问题