在重定向用户之前捕获外部链接

时间:2011-07-14 13:38:07

标签: php function preg-replace

我需要让我的用户知道他们正在点击外部链接。我的网站上有很多种聊天,有时用户发布链接,这些链接对他们来说可能是危险的,所以我想在离开网站之前警告他们。

例如,eveonline.com在其论坛上使用以下内容:http://www.eveonline.com/externalLink.aspx?l=http://altdevblogaday.com/2011/07/11/the-hidden-evil-of-the-micro-transaction/

每当链接显示时,他们会看到该域名是否与eveonline.com不同,如果是,则会向其添加“http://www.eveonline.com/externalLink.aspx?l=”。

这是我的makeClickableLinks函数,我用它来使链接可点击,我想知道是否有人可以重写,如果我做上述+可点击,因为我没有写这个功能,因为我对preg_match一无所知。

function makeClickableLinks($text)
    {
    $text = eregi_replace('(((f|ht){1}tp://)[-a-zA-Z0-9@:%_\+.~#?&//=]+)','<a target="_blank" href="\\1">\\1</a>', $text);

    $text = eregi_replace('([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_\+.~#?&//=]+)','\\1<a target="_blank" href="http://\\2">\\2</a>', $text);


    return $text;
    }

变量$ text是用户的帖子。

1 个答案:

答案 0 :(得分:1)

我不是PHP向导,但试一试。请注意,几乎所有这些都直接来自PHP手册here

function makeClickableLinks($text)
{
    $text = eregi_replace('(((f|ht){1}tp://)[-a-zA-Z0-9@:%_\+.~#?&//=]+)',
                          '<a target="_blank" href="\\1">\\1</a>', $text);      

    $text = eregi_replace('([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_\+.~#?&//=]+)',
                          '\\1<a target="_blank" href="http://\\2">\\2</a>', 
                          $text);

    $regex = '@(<a.*?href=")((?!(?:(?:f|ht)tps?://)?(?:[a-z0-9]+\.)?domain\.com)[^"]*)@i';
    $replacement = '$1http://your.domain.com/externLink.php?l=$2';

    $text = preg_replace($regex, $replacement, $text);

    return $text;
}
相关问题