2010-12-06 14 views
0

外部リンクにtarget="_blank"属性を追加できるようにこの関数を変更するには? example.comPHPのリンクRegex

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

答えて

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" 
    ); 
?> 

基本的に同じものにマッチ/置き換えられた2つの式を使用する理由を理解できませんでした。あなたの方法を少し簡略化。

また、記録のため。 HTMLはの正規表現ではないので、どのような形式でも正規表現で解析することができます。上記のような単純なケースでは、うまく動作します。

+0

まあ、ありがとう、しかし、このすべてのリンクを使用して外部として開きます。 –

+0

私はexample.com(my)とexample1.net(external)の違いに合わせる必要があります –

+0

私はそれを見つけるでしょう。ありがとう。 –

2

としてデフォルトのドメインを取る解析HTMLは、unestable高価で、言葉では、地獄です。 Simple HTML DOM Parserを使用してください。