2014-07-07 3 views
0

안녕하세요. URL 텍스트를 링크로 성공적으로 변경할 수 있지만 URL이없는 텍스트를 표시하는 데 문제가 있습니다. preg_replace는 URL이없는 텍스트를 표시하지 않습니다.

시도하고 도와 호야 시도 해 봤나 ... 거기에 URL을하지 않는 것은 preg_replace을 사용하기 전에 preg_match으로 테스트 할 필요가 없습니다

<?php 
$textorigen = $row_get_tweets['tweet']; 

// URL starting with http:// 
$reg_exUrl = "/(^|\A|\s)((http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,4} (\/\S*)?)/"; 
if(preg_match($reg_exUrl, $textorigen, $url)) { 

// make the urls hyper links 
$text_result=preg_replace($reg_exUrl, "$1<a href=\"$2\">$2</a> ", $textorigen); 
$textorigen=$text_result; 

} else { 

// if no urls in the text just return the text 
$text_result=$textorigen; 
} 

    // URL starting www. 
    $reg_exUrl = "/(^|\A|\s)((www\.)[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,4}(\/\S*)?)/"; 
    if(preg_match($reg_exUrl, $text_result, $url)) { 

    // make the urls hyper links 
    $text_result=preg_replace($reg_exUrl, "$1<a href=\"http://$2\">$2</a>", $text_result); 
    $textorigen=$text_result; 

    echo $textorigen; 
    } 
    ?> 

답변

0

:

따라서 귀하의 if-then-else 구조는 같은 것으로 간단하게 할 수 그것은 효율적으로 URL (정확도와 성능 사이의 타협)을 설명하는 가장 좋은 패턴을 발견하는 것은 매우 어렵다 . 이것이 URL의 기본 설명을 사용하여 방법을 구성하는 이유입니다. 약

코드 : 당신은 preg_replace_callback 예에 한 번만 문자열을 구문 분석하는보다 효율적인 방법으로 같은 작업을 수행 할 수 있습니다

$textorigen = <<<'DATA' 
abcd http://example.com efgh (ftps://example2.com/) ijkl www.example3.com 
DATA; 

$pattern = '~(?<=^|\s|\pP)(?:(ht|f)tps?://|www\.)\S+(?<![^\PP?/])(?=\s|$|\pP)~i'; 

$textorigen = preg_replace_callback($pattern, function ($m) { 
        $link = ($m[1])? $m[0] : 'http://' . $m[0]; 
        return '<a href="' . $link . '">' . $link . '</a>'; }, 
            $textorigen); 
echo $textorigen; 

패턴 설명 :

~     # pattern delimiter 
(?<=^|\s|\pP)  # lookbehind : preceded by the start of the string 
        # or a whitespace character or a punctuation character 
(?:    # non capturing group 
    (ht|f)tps?:// # scheme 
    |    # OR 
    www\.   # www. 
) 
\S+    # one or more non whitespace characters 
(?<![^\PP?/])  # that don't end with a punctuation character 
        # except "?" and "/" 
(?=\s|$|\pP)  # followed by a whitespace, the end of the string 
        # or a punctuation character 
~i     # end delimiter, the pattern is case insensitive 
+0

가 대단히 감사합니다 .. 초보자가 코드를 사용해 보았습니다 .couldn't는 일할 수 있습니다. 어떻게 사용합니까? 감사합니다. – user3813986

+0

@ user3813986 : 예제 코드를 추가하겠습니다. –

+0

알겠습니다 감사합니다 기다리고있을 것입니다 – user3813986

1

.Thanks. preg_replace은 일치하는 항목 만 바꿉니다. 정규식 패턴에 대해

$replaced = preg_replace($regex,$replacement,$original); 
관련 문제