php 如何从php中的内容中删除链接?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3830717/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to remove a link from content in php?
提问by Adrian
How can i remove the link and remain with the text?
如何删除链接并保留文本?
text text text. <br><a href='http://www.example.com' target='_blank' title='title' style='text-decoration:none;'>name</a>
like this:
像这样:
text text text. <br>
i still have a problem.....
我还是有问题.....
$text = file_get_contents('http://www.example.com/file.php?id=name');
echo preg_replace('#<a.*?>.*?</a>#i', '', $text)
in that url was that text(with the link) ...
在那个网址中是那个文本(带有链接)......
this code doesn't work...
此代码不起作用...
what's wrong?
怎么了?
Can someone help me?
有人能帮我吗?
回答by luchaninov
I suggest you to keep the text in link.
我建议您将文本保留在链接中。
strip_tags($text, '<br>');
or the hard way:
或艰难的方式:
preg_replace('#<a.*?>(.*?)</a>#i', '', $text)
If you don't need to keep text in the link
如果您不需要在链接中保留文本
preg_replace('#<a.*?>.*?</a>#i', '', $text)
回答by Ryan Chouinard
While strip_tags()
is capable of basic string sanitization, it's not fool-proof. If the data you need to filter is coming in from a user, and especially if it will be displayed back to other users, you might want to look into a more comprehensive HTML sanitizer, like HTML Purifier. These types of libraries can save you from a lot of headache up the road.
虽然strip_tags()
能够进行基本的字符串消毒,但并非万无一失。如果您需要过滤的数据来自用户,特别是如果它会显示回其他用户,您可能需要查看更全面的 HTML 消毒剂,如HTML Purifier。这些类型的库可以让您免于头痛。
strip_tags()
and various regex methods can't and won't stop a user who really wants to inject something.
strip_tags()
并且各种正则表达式方法不能也不会阻止真正想要注入某些东西的用户。
回答by methodin
Try:
尝试:
preg_replace('/<a.*?<\/a>/','',"test test testa<br> <a href='http://www.example.com' target='_blank' title='title' style='text-decoration:none;'>name</a>");
回答by Alan Haggai Alavi
strip_tags()
will strip HTML tags.
strip_tags()
将剥离 HTML 标签。
回答by Vu Anh
this is my solutions :
这是我的解决方案:
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,'',$rs);
$str = str_replace($rs,$text,$str);
}
return $str;}
回答by icaksama
Try this one. Very simple!
试试这个。很简单!
$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);
Output:
输出:
text text text. <br>
回答by dmikam
One more short solution without regexps:
另一种没有正则表达式的简短解决方案:
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;
}
}
?>