2013-06-17 9 views
0

Tehre가 최선의 방법을 수행하는 방법에 대한 분명한 대답은 아닙니다.bbcode 링크 + 비 bbcode URL에 대한 REGEX

[URL = HTTP : //thisisalink.com] 링크 [/ URL]

뿐만 아니라 가능한 복사/붙여 넣기 URL을 :

나는 BBCode의 형식으로 링크를 수있는 몇 가지 BBCode는이

http://thisisalink.com

두 인스턴스를 클릭 가능한 링크로 대체하려고합니다. 나는 현재 다음과 같은 것을 가지고있다 : 정규식 실행 :

"/\[link=http:\/\/(.*?)\](.*?)\[\/link\]/is" 
"/\[link=https:\/\/(.*?)\](.*?)\[\/link\]/is" 
"/\[link=(.*?)\](.*?)\[\/link\]/is" 

$URLRegex = '/(?:(?<!(\[\/link\]|\[\/link=))(\s|^))'; // No [url]-tag in front and is start of string, or has whitespace in front 
$URLRegex.= '(';         // Start capturing URL 
$URLRegex.= '(https?|ftps?|ircs?):\/\/';   // Protocol 
$URLRegex.= '\S+';         // Any non-space character 
$URLRegex.= ')';         // Stop capturing URL 
$URLRegex.= '(?:(?<![[:punct:]])(\s|\.?$))/i';  // Doesn't end with punctuation and is end of string, or has whitespace after 

나는 둘 다 일할 수 없을 것 같다. 이 경우 마지막 정규식은 첫 번째 정규식의 연결을 끊는 것 같습니다.

분명히 bbcode 링크와 붙여 넣은 URL을 서로 충돌하지 않고 함께 연결하는 가장 좋은 방법은 문서화되어 있습니다. 난/두 배 사본을 캡처 붙여 넣은

$pattern = '~\[url\s*+=\s*+([^]\s]++)]([^[]++)\[/url]|((http://\S++))~i'; 
$result = preg_replace($pattern, '<a href="$1$3">$2$4</a>', $string); 

참고 : 당신이 할 수있는

답변

0

나는 이것으로 끝났다. 나는 그 다음 php에서 몇 가지 링크 검사를 위해 특별한 코드를 할 수있게 해주는 콜백을 전달했다 :

# MATCH '?://www.link.com' and make it a bbcode link 
$URLRegex = '/(?:(?<!(\[\/link\]|\[\/link=))(\s|^))'; // No [url]-tag in front and is start of string, or has whitespace in front 
$URLRegex.= '(';         // Start capturing URL 
$URLRegex.= '(https?|ftps?|ircs?|http?|ftp?|irc?):\/\/';   // Protocol 
$URLRegex.= '\S+';         // Any non-space character 
$URLRegex.= ')';         // Stop capturing URL 
$URLRegex.= '(?:(?<![[:punct:]])(\s|\.?$))/i'; 
$output = preg_replace($URLRegex, "$2[link=$3]$3[/link]$5", $output); 

# MATCH 'www.link.com' and make it a bbcode link 
$URLRegex2 = '/(?:(?<!(\[\/link\]|\[\/link=))(\s|^))'; // No [url]-tag in front and is start of string, or has whitespace in front 
$URLRegex2.= '(';         // Start capturing URL 
$URLRegex2.= 'www.';   // Protocol 
$URLRegex2.= '\S+';         // Any non-space character 
$URLRegex2.= ')';         // Stop capturing URL 
$URLRegex2.= '(?:(?<![[:punct:]])(\s|\.?$))/i'; 
$output = preg_replace($URLRegex2, "$2[link=http://$3]$3[/link]$5", $output); 


# link up a [link=....]some words[/link] 
$output = preg_replace_callback(
    "/\[link=(.*?):\/\/(.*?)\](.*?)\[\/link\]/is", 
    Array($this,'bbcode_format_link1'), 
    $output); 
2

예를 들어, BBCode는 태그 내부에 링크의 교체를 피하기 위해 BBCode의 패턴으로 시작 교대를 사용하는 것입니다 url은 preg_replace_callback 기능을 사용하지 마십시오.

복사/붙여 넣기 URL에 단순화 된 패턴을 사용했지만 https, ftp, ftps ...을 처리하려는 것으로 대체 할 수 있습니다.