2010-12-06 3 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" 
    ); 
?> 

기본적으로 일치하는/바꾸어 진 두 표현식을 사용하는 이유를 알 수 없습니다. 약간의 방법을 간소화했습니다.

또한 기록을 위해. HTML은 정규이 아니므로 정규 표현식으로 구문 분석 할 수 있습니다. 위와 같은 단순한 경우에는 잘 작동합니다.

+0

글쎄, 고마워,하지만이 모든 링크를 사용하여 외부로 열립니다. –

+0

example.com (내)과 example1.net (외부)의 차이점을 일치시켜야합니다. –

+0

사용 방법을 알려드립니다. 감사. –