2013-10-27 3 views
2

다음과 같은 PHP 코드가 JS be에서 다시 작성되므로 텍스트 모양의 내부 URL 링크가 html 링크로 대체 될 수 있습니까? jsfiddle을 시작했습니다.JS : 텍스트에서 URL 찾기, 링크 만들기

<?php 

// The Regular Expression filter 
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/"; 

// The Text you want to filter for urls 
$text = "The text you want to filter goes here. http://google.com"; 

// Check if there is a url in the text 
if(preg_match($reg_exUrl, $text, $url)) { 

    // make the urls hyper links 
    echo preg_replace($reg_exUrl, "<a href="{$url[0]}">{$url[0]}</a> ", $text); 

} else { 

    // if no urls in the text just return the text 
    echo $text; 

} 
?> 

답변

3

사용이 :

var text = "The text you want to filter goes here. http://google.com"; 
text = text.replace(
    /((http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?)/g, 
    '<a href="$1">$1</a>' 
); 

설명 :

여기 g 글로벌 플래그입니다; 그것은 모든 URL을 대체 할 것입니다.

또한 전체 표현식에 대한 캡처 그룹을 추가했기 때문에 역 참조 $1을 사용할 수 있습니다.

관련 문제