2010-08-10 5 views
0

PHP에서 일반 텍스트 URL을 HTML 하이퍼 링크로 변환하는 방법이 있습니까? 나는 다음과 같은 형식의 URL을 변환해야합니다PHP에서 일반 텍스트 URL을 HTML 하이퍼 링크로 변환

http://example.com 
http://example.org 
http://example.gov/ 
http://example.com?q=sometext&opt=thisandthat 
http://example.com#path 
http://example.com?q=querypath#path 
http://example.com/somepath/index.html 

https://example.com/ 
https://example.org/ 
https://example.gov/ 
https://example.com?q=sometext&opt=thisandthat 
https://example.com#path 
https://example.com?q=querypath#path 
https://example.com/somepath/index.html 

http://www.example.com/ 
http://www.example.org/ 
http://www.example.gov/ 
http://www.example.com?q=sometext&opt=thisandthat 
http://www.example.com#path 
http://www.example.com?q=querypath#path 
http://www.example.com/somepath/index.html 

https://www.example.com/ 
https://www.example.org/ 
https://www.example.gov/ 
https://www.example.com?q=sometext&opt=thisandthat 
https://www.example.com#path 
https://www.example.com?q=querypath#path 
https://www.example.com/somepath/index.html 

www.example.com/ 
www.example.org/ 
www.example.gov/ 
www.example.com?q=sometext&opt=thisandthat 
www.example.com/#path 
www.example.com?q=querypath#path 
www.example.com/somepath/index.html 

example.com/ 
example.org/ 
example.gov/ 
example.com?q=sometext&opt=thisandthat 
example.com/#path 
example.com?q=querypath#path 
example.com/somepath/index.html 
+0

php를 사용하여 구문 분석하려는 외부 파일에서 오는 것입니까? – Sarfraz

+0

링크에서 무엇을 읽고 싶습니까? 이 링크는 파일 또는 배열 또는 다른 것입니까? –

+0

텍스트에서 이러한 URL을 찾고 전체 URL로 변환하고 HTML 링크로 바꾸는 방법을 찾고 계신 것 같군요. 맞습니까? – Gumbo

답변

0

어, 앵커 태그를 포장?

function linkify($url) { 
    return '<a href="' . $url . '">' . $url . '</a>'; 
} 
+0

URL의 HTML 이스케이프를 수행하지 않으므로이 코드는 작동하지 않습니다. 가장 중요한 것은 앰퍼샌드가 포함 된 URL이 잘못된 HTML을 생성한다는 것입니다. –

+0

그것은 모든 것들을하지 않습니다. 나는 그 개념을 보여준 가장 작은 예를 그려 보았다. –

2

당신은 단지 하나의 URL을 변환해야하는 경우입니다 :

function makeLink($url) 
{ 
    return '<a href="' . htmlspecialchars($url) . '">' . htmlspecialchars($url) . '</a>'; 
} 

큰 텍스트 블록에 나타나는 URL의 경우

+0

여분의 점에 대해 지역 변수를 나타내는 의도를 사용하고 htmlspecialcharacters()를 두 번 호출하지 마십시오. –

+0

중복 코드입니다. 그렇지만'htmlspecialchars ($ url)'은 의도와 변수 이름을 모두 나타냅니다. 할 수 있었다. :-) –

0

이것은 내가 만든 작은 포럼에 같은 일을하는 데 사용하는 것입니다 : 사용자의 의견은이 질문을 참조하십시오. 일반적으로 나는 그것을 통해 전체 설명을 실행합니다. echo makeLinks($forumpost['comment']);

function makeLinks($str) {  
    return preg_replace('/(https?):\/\/([A-Za-z0-9\._\-\/\?=&;%,]+)/i', '<a href="$1://$2" target="_blank">$1://$2</a>', $str); 
} 
2

이 기능을 사용해보십시오. 텍스트가 http 또는 www로 시작하는 경우 링크가 작성됩니다. example.com은 작동하지 않습니다.

function linkable($text = ''){ 
    $text = preg_replace("/\s+/", ' ', str_replace(array("\r\n", "\r", "\n"), ' ', $text)); 
    $data = ''; 
    foreach(explode(' ', $text) as $str){ 
     if (preg_match('#^http?#i', trim($str)) || preg_match('#^www.?#i', trim($str))) { 
      $data .= '<a href="'.$str.'">'.$str.'</a> '; 
     } else {`enter code here` 
      $data .= $str .' '; 
     } 
    } 
    return trim($data); 
} 
관련 문제