2012-02-04 105 views
1

下面我有一個簡單的(BB代碼)爲PHP代碼插入到代碼的註釋/後。在preg_replace函數的第二或第三項應用功能(preg_replace_callback?)

function highlight_code($str) { 
    $search = array( 
        '/\[code=(.*?),(.*?)\](((?R)|.)*?)\[\/code\]/is', 
        '/\[quickcode=(.*?)\](((?R)|.)*?)\[\/quickcode\]/is' 
        ); 

    $replace = array( 
      '<pre title="$2" class="brush: $1;">$3</pre>', 
      '<pre class="brush: $1; gutter: false;">$2</pre>' 
      ); 

    $str = preg_replace($search, $replace, $str); 
    return $str; 
} 

我希望能夠做的是插入功能,在這些地點:

$replace = array( 
      '<pre title="$2" class="brush: $1;">'.myFunction('$3').'</pre>', 
                 ^here 
      '<pre class="brush: $1; gutter: false;">'.myFunction('$2').'</pre>' 
                  ^here 
      ); 

從我讀過,所以我可能需要使用preg_replace_callback()或電子改性劑,但我無法弄清楚如何去做這件事。我用正則表達式的知識不太好。希望得到一些幫助!

回答

1

您可以使用此代碼段(E-修改):

function highlight_code($str) { 
    $search = array( 
        '/\[code=(.*?),(.*?)\](((?R)|.)*?)\[\/code\]/ise', 
        '/\[quickcode=(.*?)\](((?R)|.)*?)\[\/quickcode\]/ise' 
        ); 
    // these replacements will be passed to eval and executed. Note the escaped 
    // single quotes to get a string literal within the eval'd code  
    $replace = array( 
      '\'<pre title="$2" class="brush: $1;">\'.myFunction(\'$3\').\'</pre>\'', 
      '\'<pre class="brush: $1; gutter: false;">\'.myFunction(\'$2\').\'</pre>\'' 
      ); 

    $str = preg_replace($search, $replace, $str); 
    return $str; 
} 

或這一個(回調):

function highlight_code($str) { 
    $search = array( 
        '/\[code=(.*?),(.*?)\](((?R)|.)*?)\[\/code\]/is', 
        '/\[quickcode=(.*?)\](((?R)|.)*?)\[\/quickcode\]/is' 
        ); 

    // Array of PHP 5.3 Closures 
    $replace = array(
        function ($matches) { 
         return '<pre title="'.$matches[2].'" class="brush: '.$matches[1].';">'.myFunction($matches[3]).'</pre>'; 
        }, 
        function ($matches) { 
         return '<pre class="brush: '.$matches[1].'; gutter: false">'.myFunction($matches[2]).'</pre>'; 
        } 
      ); 
    // preg_replace_callback does not support array replacements. 
    foreach ($search as $key => $regex) { 
     $str = preg_replace_callback($search[$key], $replace[$key], $str); 
    } 
    return $str; 
} 
+0

感謝您的幫助嗨。與第一種方法遇到錯誤:'解析錯誤:語法錯誤,意想不到的「[」在:正則表達式code'和'致命錯誤:的preg_replace()[function.preg-replace]:無法評估代碼:...(上載) ''preg_replace'執行時都會發生。用第二種方法,我得到了'parse error:syntax error,unexpected T_FUNCTION,expect'')''用函數($ matches){'。有任何想法嗎?我希望能夠使用您提出的第一種方法。 – sooper 2012-02-04 19:27:28

+0

其實,第一個版本可行,但我現在有另一個問題。當'$ str'包含方括號時,我會得到上面的錯誤。任何想法爲什麼?看來,如果我輸入任何不是文本的東西,我會得到錯誤。 – sooper 2012-02-04 19:34:54

+0

對於第二個版本PHP 5.3是必需的。你真的應該更新你的PHP,因爲評估永遠是邪惡的,PHP 5.2不再受支持。但我只是修正了eval版本(缺少單引號)。 – TimWolla 2012-02-04 21:00:52

相關問題