1

我在下面有一个简单的(BBCode)PHP 代码,用于将代码插入评论/帖子。

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
            );  

根据我在 SO 上阅读的内容,我可能需要使用preg_replace_callback()或 e-modifier,但我无法弄清楚如何去做;我对正则表达式的了解不是很好。将不胜感激一些帮助!

4

1 回答 1

1

您可以使用此代码段(电子修饰符):

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;  
} 
于 2012-02-04T18:59:09.800 回答