开发者

How to remove a link from content in php?

开发者 https://www.devze.com 2023-01-18 09:48 出处:网络
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>

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?


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)


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.


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


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


A version from the above compiled notes:

$withoutlink = preg_replace('/<a.*>(.*)<\/a>/isU','$1',$String);


strip_tags() will strip HTML tags.


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>


Try:

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

Note: this code remove link with text.


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

精彩评论

暂无评论...
验证码 换一张
取 消