2011-03-12 3 views
1

내가 사용하고 다음과 같은 기능 :간단한 위키 파서와 링크 자동 감지

function MakeLinks($source){ 
return preg_replace('!(((f|ht){1}tp://)[-a-zA-Zа-яА-Я()[email protected]:%_+.~#?&;//=]+)!i', '<a href="/1">$1</a>', $source); 
} 

function simpleWiki($text){ 
$text = preg_replace('/\[\[Image:(.*)\]\]/', '<a href="$1"><img src="$1" /></a>', $text); 
return $text; 
} 

첫 번째는 http://example.com 링크로 http://example.com 변환합니다.

번째 기능은 이미지에 [[Image:http://example.com/logo.png]] 같은 문자열을 전환.

이제

나는 텍스트를

$text = 'this is my image [[Image:http://example.com/logo.png]]'; 

이이 simpleWiki(makeLinks($text)) 같은 변환이 비슷한 출력하는 경우 :

this is my image <a href="url"><img src="<a href="url">url</a>"/></a> 

가 어떻게이 문제를 방지 할 수 있습니까? URL이 [[Image:URL]] 구성의 일부가 아닌지 확인하는 방법은 무엇입니까? 에서

답변

1

귀하의 즉각적인 문제가 하나 (둘과 대안)에 두 식을 결합하여 해결 한 후 사용 할 수 그리 잘 known- 그러나-매우 강력한 : preg_replace_callback() 때문에 추천 대상 문자열을 통해 한 번에 개별적으로 각각의 경우를 취급 기능 :

<?php // test.php 20110312_1200 
$data = "[[Image:http://example.com/logo1.png]]\n". 
     "http://example1.com\n". 
     "[[Image:http://example.com/logo2.png]]\n". 
     "http://example2.com\n"; 

$re = '!# Capture WikiImage URLs in $1 and other URLs in $2. 
     # Either $1: WikiImage URL 
     \[\[Image:(.*?)\]\] 
    | # Or $2: Non-WikiImage URL. 
     (((f|ht){1}tp://)[-a-zA-Zа-яА-Я()[email protected]:%_+.~#?&;//=]+) 
     !ixu'; 

$data = preg_replace_callback($re, '_my_callback', $data); 

// The callback function is called once for each 
// match found and is passed one parameter: $matches. 
function _my_callback($matches) 
{ // Either $1 or $2 matched, but never both. 
    if ($matches[1]) { // $1: WikiImage URL 
     return '<a href="'. $matches[1] . 
      '"><img src="'. $matches[1] .'" /></a>'; 
    } 
    else {    // $2: Non-WikiImage URL. 
     return '<a href="'. $matches[2] . 
      '">'. $matches[2] .'</a>'; 
    } 
} 
echo($data); 
?> 

이 스크립트는 예를 구현 우리의 두 정규식은 당신이 요구하는 것을 수행합니다. 욕심 버전이 제대로 작동하지 않기 때문에 나는 (.*?) 게으른 버전으로 욕심 (.*)을 변경 않았다 있습니다 (이것은 여러 WikiImages을 처리하는 데 실패). 또한 정규 표현식에 'u' 수정자를 추가했습니다 (패턴에 유니 코드 문자가 포함되어있을 때 필요함). 보시다시피, 프리 콜백 함수는 매우 강력합니다. (이 기술은 할 수 있습니다 꽤 무거운, 텍스트 처리 현명한.)

그러나, 당신은 URL을 골라 사용하는 정규식 크게 개선 할 수 있다는 점을 유념하십시오. 더 "Linkifying"의 URL에 대한 자세한 내용은 다음 리소스를 확인 (힌트 : "개는"한 무리가 있습니다) :
The Problem With URLs
An Improved Liberal, Accurate Regex Pattern for Matching URLs
URL Linkification (HTTP/FTP)

1

MakeLinks 아래 참조,이 [^:"]{1}을 추가

function MakeLinks($source){ 
    return preg_replace('![^:"]{1}(((f|ht){1}tp://)[-a-zA-Zа-яА-Я()[email protected]:%_+.~#?&;//=]+)!i', '<a href="/1">$1</a>', $source); 
} 

을 만 링크를하지 않고 ":"전에 (이미지에 :)있을 것 같은 변환. 그리고 $text = simpleWiki(MakeLinks($text));을 사용하십시오.

편집 : 당신이로 변경할 수 있습니다 preg_replace('![[:space:]](((f|ht){1}tp://)[-a-zA-Zа-яА-Я()[email protected]:%_+.~#?&;//=]+)[[:space:]]!i', '<a href="$1">$1</a>', $source);

+2

가 참고 : '{1}'필요하지 않습니다이 : 그것을 그냥 정규식을 버린다. –