0

I have a function that removes all links from a string in this format: .... It will only remove links to domains not in an array. If the domain for the link isn't in the array, it will remove the link tags, and only have the inner html from the link.

It looks like this:

if(!function_exists("checkLink")){ 

    function checkLink($link, $text){ 
        $safe_domains[] = "domain1.com"; 
        $safe_domains[] = "domain2.com"; 

        $prefix = ""; 

        if(substr($link, 0, 8) == "mailto:"){ 
            // do nothing - link is fine 
        } 
        else{ 
            $url = @parse_url($link, PHP_URL_HOST); 
            $dolink = false; 
            foreach($safe_domains as $domain){ 
                if(strpos($url, $domain) !== FALSE){ 
                    $dolink = true; 
                    break; 
                } 
            } 

            if(!$dolink){ 
                return preg_replace("/<\\/?a(\\s+.*?>|>)/", "", $text); 
            } 

        } 

        return "<a href=\"$link\" target=\"_blank\">$text</a>"; 

    } 
} 

$post['message'] = preg_replace("/<a href=\\\"(.*?)\\\" target=\\\"_blank\\\">(.*?)<\/a>/ime", 'checkLink("$1", "$2")',$post['message']);

However, the problem is, that though it works fine with a link like this:

<a href="http://example.com" target="_blank">Link text</a>

It won't work if there is a linebreak in the link, like this:

<a href="http://example.com" target="_blank">Link 
text</a>

Anyone with a solution for this? Thanks!

Fabio Cardoso
  • 1,181
  • 1
  • 14
  • 37
  • What does it do in the second case? Error? Something else? – Nick Pickering Feb 24 '13 at 13:39
  • 2
    Don't use regular expressions for this kind of stuff. [Here's a solution using a HTML parser](http://stackoverflow.com/questions/14804182/php-remove-links-to-specific-website-but-keep-text/14804316#14804316) – nice ass Feb 24 '13 at 13:40
  • 1
    Add the `s` modifier -> http://php.net/manual/en/reference.pcre.pattern.modifiers.php The `s` modifier makes `.` in the pattern match newlines as well. – Jon Feb 24 '13 at 13:41

0 Answers0