我最初使用Regex就这些问题提出了一个问题,但建议使用PHP DOM库来代替……这是优越的,但我仍然卡住了.
基本上,我想包装一个< a>的内容.在< span>中如果它还没有包含在< span>中.
PHP
$input = <<
它提供了这个输出:
PHP Warning: DOMDocumentFragment::appendXML(): Entity: line 1: parser error : Premature end of data in tag img line 1 in /private/var/folders/78/78vHGigZHcuFeXB1KKJSb++++TI/-Tmp-/untitled_3xd..PHP on line 24
PHP Warning: DOMDocumentFragment::appendXML(): Image Link in /private/var/folders/78/78vHGigZHcuFeXB1KKJSb++++TI/-Tmp-/untitled_3xd..PHP on line 24
PHP Warning: DOMDocumentFragment::appendXML(): ^ in /private/var/folders/78/78vHGigZHcuFeXB1KKJSb++++TI/-Tmp-/untitled_3xd..PHP on line 24
PHP Warning: DOMNode::appendChild(): Document Fragment is empty in /private/var/folders/78/78vHGigZHcuFeXB1KKJSb++++TI/-Tmp-/untitled_3xd..PHP on line 25
这主要是有效的,除了它真的很挑剔,并且你可以看到它死了,如果这里是一个img(或类似的)标签在一个href内.
什么是使这项工作的最佳方式.我现在一直在为一个令人尴尬的尴尬而奋斗.
编辑
根据以下反馈,这里是修改后的代码和输出.请注意,img标记之前的文本由于某种原因未被包装.有任何想法吗?
$doc = new DOMDocument();
$doc->loadHTML($input);
$tags = $doc->getElementsByTagName('a');
foreach ($tags as $tag) {
$spancount = $tag->getElementsByTagName("span")->length;
if($spancount == 0){
$element = $doc->createElement('span');
$element->setAttribute('style','color:#ffffff;');
foreach ($tag->childNodes as $child) {
$tag->removeChild($child);
$element->appendChild($child);
}
$tag->appendChild($element);
}
}
echo $doc->saveHTML();
输出:
if($spancount == 0){
$element = $doc->createElement('span');
$element->setAttribute('style','color:#ffffff;');
$tag->parentNode->replaceChild($element,$tag);
$element->apendChild($tag);
}
编辑哎呀,看起来你正在尝试将所有内容包装在范围内的$tag下…试试这个:
if($spancount == 0){
$element = $doc->createElement('span');
$element->setAttribute('style','color:#ffffff;');
foreach ($tag->childNodes as $child) {
$tag->removeChild($child);
$element->appendChild($child);
}
$tag->appendChild($child);
}
编辑2根据您的结果,由于节点删除,看起来foreach没有完成…尝试用以下方法替换foreach:
while ($tag->childNodes->length > 0) {
$child = $tag->childNodes->item(0);
$tag->removeChild($child);
$element->appendChild($child);
}