I have this variable ($contents) which stores a lines of text that may include some words with links..what I need to do is to remove all the links in ($contents)
How can I do this?
Removing links
<?php
$link_pattern = "/(<a href=\"[a-zA-Z0-9\.\/_-]*\" [a-zA-Z0-9.\"\.]*?>)/";
preg_match($link_pattern, $contents, $links);
foreach($links as $link)
{
$contents = str_replace($link, '', $contents);
}
$contents = str_replace('</a>', '', $contents);
?>
The pattern may need some tweaking, but that's pretty much the gist of it. Set up a pattern to look for any link and grab all the links to an array. Then just loop through the array and using str_replace() replace the link with nothing (''). Then just clean it up by replacing all the "</a>" since there won't be any links.
~Brett
this bit of code should do it for you
$contents = preg_replace('/<a [^>]+>(.*?)<\/a>/i', "$1", $contents);
I tried it and it didn't work!!
the code i tested it with was this, and it worked fine...
<?php
$contents = '<a href="http://site.net">First link</a> and more text and another <a class="links" href="http://site.com">link here</a> with more text and one last <a href="http://mysite.com" target="_new">link again</a>.';
$contents = preg_replace('/<a [^>]+>(.*?)<\/a>/i', "$1", $contents);
echo $contents;
?>
its working! :-D