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


Applying function on second or third term in 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
            );  

从我在SO上读到的内容来看,我可能需要使用preg_replace_callback()或电子修改器,但我不知道如何做到这一点;我对regex的了解不是很好。非常感谢您的帮助!

您可以使用以下代码段(e-modifier):

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