[英]How do i parse HTML and replace specific tags using DOMDocument
我有一个要加载为DOMDocument并替换特定标签的文本。
<a href="https://www.google.co.in/dsfethtrw">link1</a>
There's only one thing people of the Internet love more than an absolutely epic
<a href="https://www.google.co.in/dsfethtrfersgest">link2</a>
mistake on live television
<a href="https://www.google.co.in/ewferagre">link3</a>
我想删除标签,输出应为:
**link1**
There's only one thing people of the Internet love more than an absolutely epic
**link2**
mistake on live television
**link3**
码:
$dom = new DOMDocument;
$dom->loadHTML($entity->body[$field_lang][0]['value']);
foreach ($dom->getElementsByTagName('a') as $node) {
$node->removeAttribute('href');
}
$entity->body[$field_lang][0]['value'] = $dom->saveHTML();
它给我的输出像:
<a>link1</a> etc...
我如何摆脱标签并仅输出文本Ex。 链接1
$ text = strip_tags($ link);
使用DOMDocument替换特定的href
$xml = new DOMDocument();
$xml->loadHTML($entity->body[$field_lang][0]['value']);
$links = $xml->getElementsByTagName('a');
//Loop through each <a> tags and replace them by their text content
for ($i = $links->length - 1; $i >= 0; $i--) {
$linkNode = $links->item($i);
$lnkText = $linkNode->textContent;
if ($url == $linkNode->attributes->item(0)->nodeValue) {
$newTxtNode = $xml->createTextNode($lnkText);
$linkNode->parentNode->replaceChild($newTxtNode, $linkNode);
}
}
$entity->body[$field_lang][0]['value'] = $xml->saveHTML();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.