2011-10-08 7 views
3

현재 PHP를 사용하여 CMS에 토큰을 추가하려고합니다.PHP RegExp Replace

사용자는 [my_include.php]과 같은 문자열을 WYSIWYG 편집기에 입력 할 수 있습니다.

include('my_include.php');

사람이 할 수 있도록 정규 표현식 및 추출 과정을 구성하여 지원할 수 : 우리는 다음과 같은 형식의 포함이 형식으로 무엇을 추출하고로 돌려 하시겠습니까? 이상적으로, 나는 그것들을 모두 하나의 배열로 추출하여, 구문 분석하기 전에 몇 가지 검사를 제공 할 수 있도록 include();?

감사합니다.

+0

어떤 CMS를 사용하고 있습니까? – Olli

+0

별주 시스템입니다. – BenM

답변

3
preg_replace('~\[([^\]]+)\]~', 'include "\\1";', $str); 

근무 샘플 : http://ideone.com/zkwX7

+0

@BenM 나중에 참조 할 수 있도록 덧글이 아닌 원래 질문에 추가 코드를 편집하십시오. 그런 식으로, 우리가 당신을 더 잘 도울 수 있도록 잘 정돈되고 이해할 수 있습니다. – Bojangles

0

preg_match_all() 사용하여, 당신이 할 수 있습니다 : 여기에 사용

$matches = array(); 

// If we've found any matches, do stuff with them 
if(preg_match_all("/\[.+\.php\]/i", $input, $matches)) 
{ 
    foreach($matches as $match) 
    { 
     // Any validation code goes here 

     include_once("/path/to/" . $match); 
    } 
} 

정규식은 \[.+\.php\]입니다. 사용자가 [hello]을 입력하면 일치하지 않으므로 일치하는 *.php 문자열과 일치합니다.

2

preg_match_all()과 함께 가고 결과를 루프로 실행하고 발견 한 내용을 바꾸기를 원할 것입니다. 다음 콜백 솔루션보다 약간 빠르지 만, PREG_OFFSET_CAPUTRE 및 substr_replace()가 사용되는 경우 조금 더 까다 롭습니다.

<?php 

function handle_replace_thingie($matches) { 
    // build a file path 
    $file = '/path/to/' . trim($matches[1]); 

    // do some sanity checks, like file_exists, file-location (not that someone includes /etc/passwd or something) 
    // check realpath(), file_exists() 
    // limit the readable files to certain directories 
    if (false) { 
    return $matches[0]; // return original, no replacement 
    } 

    // assuming the include file outputs its stuff we need to capture it with an output buffer 
    ob_start(); 
    // execute the include 
    include $file; 
    // grab the buffer's contents 
    $res = ob_get_contents(); 
    ob_end_clean(); 
    // return the contents to replace the original [foo.php] 
    return $res; 
} 

$string = "hello world, [my_include.php] and [foo-bar.php] should be replaced"; 
$string = preg_replace_callback('#\[([^\[]+)\]#', 'handle_replace_thingie', $string); 
echo $string, "\n"; 

?>