Link to home
Start Free TrialLog in
Avatar of ellandrd
ellandrdFlag for Ireland

asked on

remove all external links from string

i have a string:

$data = '<p>Click here to <a href="http://www.mysite.com/contact.html" title="Contact us">contact us</a> or <a href="about.html" title="About us">read more about us</a> or click here to <a href="mailto:info@mysite.com" title="Email us">email us</a> or visit my friends site at <a href="http://www.anothersite.com" title="Friends site">http://www.anothersite.com</a> to speak to contact him.</p>';

Basically what i would like is to do is remove the <a></a> tags from all external links.  So my string would look like this:

$data = '<p>Click here to <a href="http://www.mysite.com/contact.html" title="Contact us">contact us</a> or <a href="about.html" title="About us">read more about us</a> or click here to <a href="mailto:info@mysite.com" title="Email us">email us</a> or visit my friends site at http://www.anothersite.com to speak to contact him.</p>';

Please advise with example snippets.
Avatar of orbic1
orbic1

function filter($badwords){

$swapbad = array(",",":",";","%","http","[url=","[/url]","//","\\","</a>","<a href");
$nobadwords = " ** ";
      foreach($swapbad as $replace){
            $badwords = str_replace($swapbad,$nobadwords,$badwords);
      }
      return $badwords;
}


just call it like filter($data);


This checks all stuff found in $data against the array and swaps it for **
Avatar of ellandrd

ASKER

that removes all links.  i only want to remove external links.

i found this previous question where the asker wanted to remove internal links but i cant make it work for only external, keeping internal links

https://www.experts-exchange.com/questions/21985319/Remove-Internal-Hyperlinks.html

Maybe you can??
$external   = 'http://';
$pos = strpos($mystring, $findme);

// Note use of ===.  Simply == would not work as expected

if ($pos === true) {
    // PUT filter in here
} else {
    // Don't do anything because http:// was not found in $data
}
then just change your "badwords" array as appropriate
ASKER CERTIFIED SOLUTION
Avatar of Richard Quadling
Richard Quadling
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
My reasoning here is that ALL external links will start with http://. But you may also have local links starting with http:// AND you may also have subdomains, so the domain has to end in "mysite.com".