【发布时间】:2011-05-03 13:28:57
【问题描述】:
我需要从某些文本中删除锚标记,但似乎无法使用正则表达式来做到这一点。
只是锚标签,而不是它们的内容。
例如,<a href="http://www.google.com/" target="_blank">google</a> 将变为 google。
【问题讨论】:
我需要从某些文本中删除锚标记,但似乎无法使用正则表达式来做到这一点。
只是锚标签,而不是它们的内容。
例如,<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 进行更改时,向后循环很重要。
【讨论】:
DOMDocument 对象。您可以使用$xml->saveHTML(); 来获取整个 html 结果。 $lnkText 包含当前链接文本作为字符串,你可能想trim它。
【讨论】:
这个问题已经回答了,但我想我会添加我的解决方案。我比公认的解决方案更喜欢这个,因为它更切中要害。
$content =
preg_replace(array('"<a href(.*?)>"', '"</a>"'), array('',''), $content);
【讨论】:
$content = preg_replace(array('"<a (.*?)>"', '"</a>"'), array('',''), $content);。
使用正则表达式:
preg_replace('/<a[^>]+>([^<]+)<\/a>/i','\1',$html);
【讨论】:
<img...>元素怎么办?
您正在寻找strip_tags()。
<?php
// outputs 'google'
echo strip_tags('<a href="http://www.google.com/" target="_blank">google</a>');
【讨论】:
strip_tags 确实没有这样做。用户贡献的笔记中有一个实现可以帮助你:php.net/manual/en/function.strip-tags.php#100054
strip_tags(),它是一个“allowable_tags”字符串:php.net/manual/en/function.strip-tags.php。
$allowable_tags 中存在的所有标签
试一试:
$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
【讨论】:
这里的许多正则表达式对我没有帮助。其中一些删除了锚点内的内容(这根本不是 OP 要求的),而不是所有的内容,其中一些会匹配任何以 a 开头的标签,等等。
这是我根据工作需要创建的。我们遇到了一个问题,将 HTML 传递给具有锚标记(具有许多数据属性和其他属性)的 wkhtmltopdf 有时会阻止 PDF 生成,所以我想在保留文本的同时删除这些。
正则表达式:
/?a([^>]*)?>/ig
在 PHP 中你可以这样做:
$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'>
【讨论】: