PHP:替换所有出现的" [CODE] ... [/ CODE]"在一个字符串中

时间:2011-11-17 14:07:04

标签: php regex tags

我有一个这样的字符串:

Here is my code sample, its not too great:

[CODE]
<?php
    echo "Some testing...";
?>
[/CODE]

I hope you enjoy.

现在我想用highlight_string($content_of_CODE)的返回值替换所有出现的[CODE] ... [/ CODE]。 [CODE] .. [/ CODE] -pair可能会在字符串中多次出现。

如何在不使用eval的情况下解决这个问题?

感谢您的帮助!

3 个答案:

答案 0 :(得分:8)

假设[CODE]块没有嵌套,preg_replace_callback()是一个完美的候选者。

preg_replace_callback('/\[CODE\](.*?)\[/CODE\]/', 'highlight_string');

答案 1 :(得分:0)

使用此正则表达式:

(?s)\[CODE\].*?\[/CODE\]

答案 2 :(得分:0)

content_of_CODE = reg_replace('/ [!\ s +!] | [\ s * / * CODE] /','',$ content_of_CODE);

相关问题