2013-02-10 51 views
0

嗯..我创建我自己一个博客,我创建了一个的preg_replace我的“上岗”,那么如果键入:的preg_replace可选比赛

[code="php"]foobar[!code] 

他打印

<script type="syntaxhighlighter" class="brush: $1; html-script: true"><![CDATA[ foobar ]]></script> 

一切运行这个了preg_replace OK:

/\[code="(.*?)"\]/ 

(前缀)

/\[!code\]/ 

(对于sufix)

但现在我想添加一个额外的选择,但检查用户键入的...想法是类似的东西:

[code="php" [1,3]] 
foo 
[!code] 

这个回报:

<script type="syntaxhighlighter" class="brush: $1; highlight: [1,3]; html-script: true">... 

否则,如果还没有的$ 2(用户仅键入[代码= “PHP”])返回此:

<script type="syntaxhighlighter" class="brush: $1; html-script: true"> 

如何在同一个preg_replace中创建此语句?预先感谢,谢谢英语不好。

编辑

我已经实现了我的解决方案与* preg_replace_callback *

+1

我敢肯定你需要使用2个独立的电话。不要以为你会用一个管理它。 – SmokeyPHP 2013-02-10 13:11:17

回答

1

您需要使用preg_replace_callback做你想做什么:

function format_prefix($matches) 
{ 
    return '<script type="syntaxhighlighter" class="brush: ' 
     . $matches[1] 
     . (isset($matches[2]) ? '; highlight: ' . $matches[2] : '') 
     . '; html-script: true">'; 
} 

$s = '[code="php"]foobar[!code]'."\n".'[code="php" [1,3]]foobar[!code]'; 

echo preg_replace_callback('/\[code="(.*?)"(?:\s+(\[\d+,\d+\]))?\]/', 'format_prefix', $s);