开发者

Need help to rewrite PHP function

I have a function that parses text form posts and if there's a link in the post it'll redirect the link to a page that warns a users about external link before they click it.

function url2link($txt) {
     $setUrl = preg_replace("/(http:\/\/|(www\.))(([^\s<]{4,68})[^\s<]*)/", '<a href="/link/$2$3" rel="nofollow">$2$4</a>', $txt);
     return $setUrl;
}

I need to modify this function by adding a check for domain in the link. If the link is from my own domain, just 开发者_开发技巧convert it into clickable link like this:

$setUrl = preg_replace("/(http:\/\/|(www\.))(([^\s<]{4,68})[^\s<]*)/", '<a href="http://$2$3" rel="nofollow" target="_blank">$2$4</a>', $txt);

but if it is a link to an external domain -- make a link point to a warning page (top example).

I am sort of stuck here because I have no idea how to add this check. There could be multiple links in a post, some may have local, some external links and some a mix.


Try with preg_replace_callback, then you can process the matches to decide whether it's your own domain or some other.


OK, as it turned out preg_replace_callback was exactly what I needed in this case. php.net documentation sucks. I found another article that made it clear what it is and how it works. I modified my function but it doesn't work... What am I missing?

function url2link($txt) {

$checkDomain = preg_replace_callback('/(http:\/\/|(www\.))(([^\s<]{4,68})[^\s<]*)/', 'linkDomain', $txt);

   function linkDomain($matches) {

    $host =  parse_url($matches[0], PHP_URL_HOST);
    $host =  ltrim($host, 'www.');

    if ($host == 'mydomain.com') {
        $setUrl = preg_replace("/(http:\/\/|(www\.))(([^\s<]{4,68})[^\s<]*)/", '<a href="http://$2$3">$2$4</a>', $matches[0]);
    } else {
        $setUrl = preg_replace("/(http:\/\/|(www\.))(([^\s<]{4,68})[^\s<]*)/", '<a href="/link/$2$3" rel="nofollow">$2$4</a>', $matches[0]);
    }
   }
   return $setUrl;
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜