我需要从一些文本中删除锚点标签,但似乎无法使用正则表达式完成。
只删除锚点标签,不删除其中的内容。
例如,<a href="http://www.google.com/" target="_blank">google</a>
将变成 google
。
确切地说,用正则表达式无法正确完成此任务。
以下是使用DOM的示例:
$xml = new DOMDocument();
$xml->loadHTML($html);
$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;
$newTxtNode = $xml->createTextNode($lnkText);
$linkNode->parentNode->replaceChild($newTxtNode, $linkNode);
}
在对DOM进行更改时,倒序循环非常重要。
这个问题已经有答案了,但我想加入我的解决方案。我喜欢这个方案比被接受的方案更简单明了。
$content =
preg_replace(array('"<a href(.*?)>"', '"</a>"'), array('',''), $content);
$content = preg_replace(array('"<a (.*?)>"', '"</a>"'), array('',''), $content);
,以防“href”不是锚标签中的第一个属性。 - David Thomasstrip_tags()
函数。<?php
// outputs 'google'
echo strip_tags('<a href="http://www.google.com/" target="_blank">google</a>');
strip_tags
确实不会这样做。有一个用户贡献的注释中提供了一个实现方法,可能会对你有帮助:http://php.net/manual/en/function.strip-tags.php#100054 - Pekkastrip_tags()
函数,这个参数是一个包含“可允许标签”的字符串:http://php.net/manual/en/function.strip-tags.php。 - Jasper$allowable_tags
中存在的所有标签。 - Pekka使用正则表达式:
preg_replace('/<a[^>]+>([^<]+)<\/a>/i','\1',$html);
<img...>
元素会怎么样? - ridgerunner尝试一下:
$str = '<p>paragraph</p><a href="http://www.google.com/" target="_blank" title="<>">google -> foo</a><div>In the div</div>';
// first, extract anchor tag
preg_match("~<a .*?</a>~", $str, $match);
// then strip the HTML tags
echo strip_tags($match[0]),"\n";
输出:
google -> foo
$text = "<a href='http://www.google.com/'>Google1</a><br>" .
"<a>Google2</a><br>" .
"<afaketag href='http://www.google.com'>Google2</afaketag><br>" .
"<afaketag>Google4</afaketag><br>" .
"<a href='http://www.google.com'><img src='someimage.jpg'></a>";
echo preg_replace("/<\/?a( [^>]*)?>/i", "", $text);
输出:
Google1<br>Google2<br><afaketag href='http://www.google.com'>Google2</afaketag><br><afaketag>Google4</afaketag><br><img src='someimage.jpg'>
DOMDocument
对象。您可以使用$xml->saveHTML();
获取整个 HTML 结果。$lnkText 包含当前链接文本作为字符串,并且您可能想修整它。 - Yann Milin