2011-03-09 7 views
1

에서 링크를 생성 내가 링크가PHP는 HTML 텍스트

<?php 
function makelink($text) 
{ 
return preg_replace('/(http\:\/\/[a-zA-Z0-9_\-\.]*?) /i', '<a href="$1">$1</a> ', $text." "); 
} 

// works 
echo makelink ("hello how http://www.guruk.com "); 

// dont work 
echo makelink ("hello how http://www.guruk.com/test.php "); 

은?>

당신이 예에서 보는 바와 같이, 그와 함께 발견 작동하는 텍스트에서 발견되는 경우 HTML 링크를 생성하는 루틴을 발견 페이지 또는 하위 디렉토리가있을 때가 아니라 도메인 전용입니다.

해당 기능이 페이지 및 하위 디렉토리에서도 작동하도록 솔루션을 제공 할 수 있습니까? 그렇게한다고

/(http\:\/\/[a-zA-Z0-9_\-\.\/]*?) /i 

:

들으 크리스는

+0

가능한 중복 : // howovertoflow.com/questions/1959062/how-to-add-anchor-tag-to-a-url-from-text-input) – outis

답변

3

문자 ?=&은 검색어 문자열이 포함 된 URL입니다. 식에 슬래시가 많이 있기 때문에 구분 기호를 /에서 !으로 변경했습니다. 또한 대소 문자를 구분하지 않는 모드 인 경우 A-Z이 필요하지 않습니다. 정규식없이

return preg_replace('!(http://[a-z0-9_./?=&-]+)!i', '<a href="$1">$1</a> ', $text." "); 
0

기대를 포함해야합니다 귀하의 정규식 URL의 끝에 대한 문자 클래스에 슬래시.

0

:

<?php 
    // take a string and turn any valid URLs into HTML links 
    function makelink($input) { 
     $parse = explode(' ', $input); 
     foreach ($parse as $token) { 
      if (parse_url($token, PHP_URL_SCHEME)) { 
       echo '<a href="' . $token . '">' . $token . '</a>' . PHP_EOL; 
      } 
     } 
    } 

    // sample data 
    $data = array(
     'test one http://www.mysite.com/', 
     'http://www.mysite.com/page1.html test two http://www.mysite.com/page2.html', 
     'http://www.mysite.com/?go=page test three', 
     'https://www.mysite.com:8080/?go=page&test=four', 
     'http://www.mysite.com/?redir=http%3A%2F%2Fwww.mysite.com%2Ftest%2Ffive', 
     'ftp://test:[email protected]:21/pub/', 
     'gopher://mysite.com/test/seven' 
    ); 

    // test our sample data 
    foreach ($data as $text) { 
     makelink($text); 
    } 
?> 

출력 :

<a href="http://www.mysite.com/">http://www.mysite.com/</a> 
<a href="http://www.mysite.com/page1.html">http://www.mysite.com/page1.html</a> 
<a href="http://www.mysite.com/page2.html">http://www.mysite.com/page2.html</a> 
<a href="http://www.mysite.com/?go=page">http://www.mysite.com/?go=page</a> 
<a href="https://www.mysite.com:8080/?go=page&test=four">https://www.mysite.com:8080/?go=page&test=four</a> 
<a href="http://www.mysite.com/?redir=http%3A%2F%2Fwww.mysite.com%2Ftest%2Ffive">http://www.mysite.com/?redir=http%3A%2F%2Fwww.mysite.com%2Ftest%2Ffive</a> 
<a href="ftp://test:[email protected]:21/pub/">ftp://test:[email protected]:21/pub/</a> 
<a href="gopher://mysite.com/test/seven">gopher://mysite.com/test/seven</a> 
[텍스트 입력에서 URL에 앵커 태그를 추가하는 방법 (HTTP의