How to remove a link from content in php?

2020-02-20 05:31发布

问题:

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?

回答1:

I suggest you to keep the text in link.

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

or the hard way:

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

If you don't need to keep text in the link

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


回答2:

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() and various regex methods can't and won't stop a user who really wants to inject something.



回答3:

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>");


回答4:

strip_tags() will strip HTML tags.



回答5:

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,'$2',$rs);
    $str = str_replace($rs,$text,$str);
}
return $str;}

dang tin rao vat



回答6:

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>


回答7:

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


标签: php hyperlink