在preg_replace中应用第二或第三项的函数(preg_replace_callback?)

时间:2012-02-04 17:48:54

标签: php preg-replace preg-replace-callback

我在下面有一个简单的(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
            );  

从我读过的内容来看,我可能需要使用preg_replace_callback()或电子修改器,但我无法弄清楚如何去做这件事;我对正则表达式的了解并不是那么好。希望得到一些帮助!

1 个答案:

答案 0 :(得分: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;  
}