2010-12-06 64 views
0

如何修改此功能,以便可以將target="_blank"屬性添加到外部鏈接? 接受默認域example.comPHP鏈接正則表達式

function makeLinks($text){ 
if(eregi_replace('(((f|ht){1}tp://)[[email protected]:%_\+.~#?&//=]+)', '<a href="\\1">\\1</a>', $text) != $text){ 
    $text = eregi_replace('(((f|ht){1}tp://)[[email protected]:%_\+.~#?&//=]+)', '<a href="\\1">\\1</a>', $text); 
    return $text; 
} 
$text = eregi_replace('(www\.[[email protected]:%_\+.~#?&//=]+)', '<a href="http://\\1">\\1</a>', $text); // ([[:space:]()[{}]) deleted from beginnig of regex 
$text = eregi_replace('([_\.0-9a-z-][email protected]([0-9a-z][0-9a-z-]+\.)+[a-z]{2,3})', '<a href="mailto:\\1">\\1</a>', $text); 
return $text; 
} 
+1

[`ereg_replace()`和`eregi_replace()`](http://php.net/ereg_replace)已棄用。你應該切換到PCRE。 – jwueller 2010-12-06 17:41:40

回答

1
<?php 
    class HtmlLinkUtility 
    { 
     public static $BaseDomain = null; 
     public static function ReplaceEmailToHtmlLink($source) 
     { 
      return preg_replace('/([_.0-9a-z-][email protected]([0-9a-z][0-9a-z-]+\.)+[a-z]{2,3})/i', 
       '<a href="mailto:\1">\1</a>', $source); 
     } 

     public static function ReplaceUrlToHtmlLink($source) 
     { 
      function replaceUrl($groups) { 
       $url = $groups[1]; 
       return '<a href="' . $url . '"' . (strpos($url, HtmlLinkUtility::$BaseDomain) !== false ? 
        ' target="_blank"' : '') . '>' . $url . '</a>'; 
      } 

      return preg_replace_callback('!(((f|ht){1}tp://)[[email protected]:%_+.~#?&//=]+)!i', 
       replaceUrl, $source); 
     } 

     public static function ReplaceTextDataToLinks($source, $baseDomain) 
     { 
      self::$BaseDomain = $baseDomain; 
      return self::ReplaceUrlToHtmlLink(self::ReplaceEmailToHtmlLink($source)); 
     } 
    } 

    echo HtmlLinkUtility::ReplaceTextDataToLinks(
     "[email protected]<br />http://www.google.com/<br />http://www.test.com/", 
     "google.com" 
    ); 
?> 

看不出爲什麼你會用兩個表達式基本匹配/替換相同的東西。稍微簡化你的方法。

另外,爲了記錄。 HTML不是常規這樣它可以用任何形式解析正則表達式。儘管如此,對於上面這種簡單的例子來說,它運行良好。

+0

嗯,謝謝,但是使用這個每個鏈接都會以外部方式打開。 – 2010-12-06 17:58:15