2012-02-04 4 views
1

글쎄, 누군가가 메시지 상자에 텍스트가있는 링크를 넣으면 링크를 활성화하는 기능입니다.PHP 링크 활성

제 질문은 누군가가 많은 링크를 예 : www.yahoo.com www.gmail.com www.facebook.com에 넣으면 하나 이상의 링크가 표시되지 않습니다. 그런 다음 첫 번째 링크는 www.yahoo.com에만 표시됩니다.

function txt2link($text){ 
    // force http: on www. 
    $text = ereg_replace("www\.", "http://www.", $text); 
    // eliminate duplicates after force 
    $text = ereg_replace("http://http://www\.", "http://www.", $text); 
    $text = ereg_replace("https://http://www\.", "https://www.", $text); 

    // The Regular Expression filter 
    $reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/"; 
    // Check if there is a url in the text 
    if(preg_match($reg_exUrl, $text, $url)) { 
     // make the urls hyper links 
     $text = preg_replace($reg_exUrl, '<a href="'.$url[0].'" rel="nofollow">'.$url[0].'</a>', $text); 
    } // if no urls in the text just return the text 
    return ($text); 
} 

$url = "Alter pot waer it your pot http://css-tricks.com/snippets/php/find-urls-in- 
     text-make-links/ you may click the link www.yahoo.com or you may see what is the 
     http://www.youtube.com say, is it right?"; 

echo txt2link($url); 

이 코드를 실행하면 결과를 확인할 수 있습니다.

아이디어가 있으십니까?

+1

모르겠다. 오늘 혼자서, 텍스트에서 URL을 추출하려고 시도한 비슷한 (그러나 다른!) 정규 표현식을 가진 12 명의 사람들을 보았습니다. 왜 이런 일이 생길까요? PHP'get_urls' 패키지의 개발자가 돈으로 가득 찬 수영장에서 수영을할까요? – Borealid

+1

내가 말할 것 인 첫번째 물건은 preg에 찬성하여 도랑 ereg 다, 지금 잠시 동안 비참하게하게되었다. – quickshiftin

+0

js를 사용하여이 클라이언트 사이트를 만드는 것에 대해 생각해 본 적이 있습니까? http://benalman.com/code/projects/javascript-linkify/docs/files/ba-linkify-js.html – Flukey

답변

2

이것은 내가 누군가에게 도움을 주었던 것입니다. 더 이상 스택이없는 곳에서는 모르겠지만 계속해서이 기능을 사용합니다. http :의 유무에 관계없이 한 번에 많은 URL을 처리합니다. 또는 www가없는 경우. 대부분의 경우,이 사실은 우리에게 약간의 정제를 할 수 있지만 모든면에서 정말 훌륭합니다.

//for finding URLs within body of text and converting them to a clickable link 
//checks DNS to see if its valid and if the link HTML already exists ignores it. 
function titleHyper($text){ 
       $text = preg_replace("/(www\.)/is", "http://", $text); 
       $text = str_replace(array("http://http://","http://https://"), "http://", $text); 
       $text = str_replace(array("<a href='", "<a href=\"", "</a>", "'>", "\">"), "", $text); 
       $reg_exUrl = "/(http|https|ftp|ftps|)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/"; 
       preg_match_all($reg_exUrl, $text, $matches); 
       $usedPatterns = array(); 
       $context = stream_context_create(array(
       'http' => array(
       'timeout' => 5 
       ) 
       )); 
       foreach($matches[0] as $pattern){ 
        if(!array_key_exists($pattern, $usedPatterns)){ 
          $usedPatterns[$pattern]=true; 
          $the_contents = @file_get_contents($pattern, 0, $context); 
          if(substr(trim($pattern), 0, 8) != "https://"){ 
          $color = "#FF0000"; 
          } 
          if (empty($the_contents)) { 
          $title = $pattern; 
          } else { 
          preg_match("/<title>(.*)<\/title>/Umis", $the_contents, $title); 
          $title = $title[1]; 
          $color = "#00FF00";      
          //$title = htmlspecialchars($title, ENT_QUOTES); //saving data to database 
          }      
          $text = str_ireplace($pattern, "<a style='font-size: 14px; background-color: #FFFFFF; color: $color;' href='$pattern' rel='nofollow' TARGET='_blank'> $title </a>", $text); 

        } 
       } 
       return $text; 
} 
// titleHyper() in action example: 
//$text = "Some sample text with WWW.AOL.com<br />http://www.youtube.com/watch?v=YaxKiZfQcX8 <br />Anyone use www.myspace.com? <br />Some people are nuts, look at this stargate link at http://www.youtube.com/watch?v=ZKoUm6z5SzU&feature=grec_index , like aliens exist or something. http://www.youtube.com/watch?v=sfN-7HczmOU&feature=grec_index and here's a secure site https://familyhistory.hhs.gov, unless you use curl or allow secure connections it will never get a title. <br /> This is a not valid site http://zzzzzzz and this is a dead site http://zwzwzwxzw.com.<br /> Lastly lets try an already made hyperlink and see what it does <a href='http://tacobell.com'>taco bell</a>"; 
//echo titleHyper($text); 
+0

해당 코드에 대해 @chris에게 감사드립니다. 하지만로드하는 데 몇 초가 걸립니다. 이유가 무엇입니까? – user1161867

+0

그것은 주어진 URL의 DNS의 유효성을 검사합니다. 그래서 AOL.com을 타이핑하면 그 링크에서 DNS를 점검하여 활성 링크인지 여부를 확인합니다. 그렇지 않으면 링크가되지 않습니다. – chris

+0

그것은 file_get_contents를 사용하여 말하기 감각으로 원시 형식으로 URL을 열며 소스를 보는 것과 비슷합니다. 비어 있거나 아무것도 반환하지 않으면 무시합니다. 그렇지 않으면 "유효한" – chris