First of all, you need to escape—or even better, replace—the delimeters as explained in the other answers.
preg_replace('~((www|http://)[^ ]+)~', '<a href="\1">\1</a>', $str);
Secondly, to further improve the regex, the $n
replacement reference syntax is preferred over \\n
, as stated in the manual으로 바꾸는 방법.
preg_replace('~((www|http://)[^ ]+)~', '<a href="$1">$1</a>', $str);
셋째, 불필요한 캡처 괄호를 사용하면 작업 속도가 느려집니다. 그들을 제거. $1
을 $0
으로 업데이트하는 것을 잊지 마십시오. 궁금한 점이 있으시면 (?:)
을 포착하지 않는 괄호입니다.
preg_replace('~(?:www|http://)[^ ]+~', '<a href="$0">$0</a>', $str);
마지막으로, 나는 \s
의 반대 짧은하고 정확한 \S
로 [^ ]+
을 대체 할 것이다. [^ ]+
은 공백을 허용하지 않지만 개행과 탭을 허용합니다. \S
하지 않습니다. 문자열 대신 공간의 줄 바꿈으로 구분에 포함 된 여러 URL이있는 경우
preg_replace('~(?:www|http://)\S+~', '<a href="$0">$0</a>', $str);
Dup는 : http://stackoverflow.com/ questions/507436/how-do-i-linkify-urls-in-a-string-with-php –