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

このスニペット(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;  
} 
于 2012-02-04T18:59:09.800 に答える