如何从PHP中的内容中删除链接?

时间:2010-09-30 13:03:48

标签: php hyperlink

如何删除链接并保留文本?

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)
该网址中的

是该文字(带链接)......

此代码不起作用...

出了什么问题?

有人可以帮助我吗?

8 个答案:

答案 0 :(得分:32)

我建议您将文字保留在链接中。

strip_tags($text, '<br>');

或艰难的方式:

preg_replace('#<a.*?>(.*?)</a>#i', '\1', $text)

如果您不需要在链接中保留文字

preg_replace('#<a.*?>.*?</a>#i', '', $text)

答案 1 :(得分:4)

虽然strip_tags()能够进行基本的字符串清理,但它并不是万无一失的。如果您需要过滤的数据来自用户,特别是如果它将显示给其他用户,您可能需要查看更全面的HTML清理程序,例如HTML Purifier。这些类型的库可以帮助您避免在路上遇到很多麻烦。

strip_tags()和各种正则表达式方法不能也不会阻止真正想要注入某些内容的用户。

答案 2 :(得分:3)

尝试:

preg_replace('/<a.*?<\/a>/','',"test test testa<br> <a href='http://www.example.com' target='_blank' title='title' style='text-decoration:none;'>name</a>");

答案 3 :(得分:1)

strip_tags()将删除HTML标记。

答案 4 :(得分:0)

这是我的解决方案:

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;}

dang tin rao vat

答案 5 :(得分:0)

尝试这个。很简单!

$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>

答案 6 :(得分:0)

试试:

$string = preg_replace( '@<(a)[^>]*?>.*?</\\1>@si', '', $string );

注意: 此代码删除带有文本的链接。

答案 7 :(得分:-1)

没有正则表达式的另一个简短解决方案:

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;
    }
}
?>
相关问题