如何删除链接并保留文本?
text text text. <br><a href='http://www.example.com' target='_blank' title='title' style='text-decoration:none;'>name</a>
像这样:
text text text. <br>
我还有问题.....
$text = file_get_contents('http://www.example.com/file.php?id=name');
echo preg_replace('#<a.*?>.*?</a>#i', '', $text)
在那个网址是那个文本(带链接)......
这段代码不起作用......
怎么了?
有人能帮我吗?
我建议你把文字保存在链接中。
strip_tags($text, '<br>');
或困难的方式:
preg_replace('#<a.*?>(.*?)</a>#i', '\1', $text)
如果您不需要在链接中保留文本
preg_replace('#<a.*?>.*?</a>#i', '', $text)
虽然strip_tags()
能够进行基本的字符串清理,但它并不是万无一失的。如果您需要过滤的数据来自用户,特别是如果它将显示给其他用户,您可能需要查看更全面的HTML清理程序,如HTML Purifier。这些类型的库可以帮助您避免在路上遇到很多麻烦。
strip_tags()
和各种正则表达式方法不能也不会阻止真正想要注入某些东西的用户。
尝试:
preg_replace('/<a.*?<\/a>/','',"test test testa<br> <a href='http://www.example.com' target='_blank' title='title' style='text-decoration:none;'>name</a>");
strip_tags()
将删除HTML标签。
这是我的解决方案:
function removeLink($str){
$regex = '/<a (.*)<\/a>/isU';
preg_match_all($regex,$str,$result);
foreach($result[0] as $rs)
{
$regex = '/<a (.*)>(.*)<\/a>/isU';
$text = preg_replace($regex,'$2',$rs);
$str = str_replace($rs,$text,$str);
}
return $str;}
试试这个吧。非常简单!
$content = "text text text. <br><a href='http://www.example.com' target='_blank' title='title' style='text-decoration:none;'>name</a>";
echo preg_replace("/<a[^>]+\>[a-z]+/i", "", $content);
输出:
text text text. <br>
一个没有正则表达式的简短解决方案:
function remove_links($s){
while(TRUE){
@list($pre,$mid) = explode('<a',$s,2);
@list($mid,$post) = explode('</a>',$mid,2);
$s = $pre.$post;
if (is_null($post))return $s;
}
}
?>