Adrian
Adrian

Reputation: 171

How to remove a link from content in php?

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?

Upvotes: 17

Views: 62546

Answers (9)

Gratia-Mira
Gratia-Mira

Reputation: 105

A version from the above compiled notes:

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

Upvotes: 1

Mahdi Akrami
Mahdi Akrami

Reputation: 643

Try:

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

Note: this code remove link with text.

Upvotes: 0

Vu Anh
Vu Anh

Reputation: 219

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

Upvotes: 4

icaksama
icaksama

Reputation: 782

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>

Upvotes: 0

dmikam
dmikam

Reputation: 1082

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

Upvotes: -1

Ryan Chouinard
Ryan Chouinard

Reputation: 2076

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.

Upvotes: 4

methodin
methodin

Reputation: 6710

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

Upvotes: 3

luchaninov
luchaninov

Reputation: 6806

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)

Upvotes: 44

Alan Haggai Alavi
Alan Haggai Alavi

Reputation: 74292

strip_tags() will strip HTML tags.

Upvotes: 0

Related Questions