2012-02-04 109 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

相关问题