使用正则表达式的PHP BBCode样式代码转换

问题描述

| 所以我有一个
[code style=PHP]<?PHP echo \"Hello World!\"; ?>[/code]
这样的标签 用户可能会在文本区域中使用大量这些标签,所以我要搜索的是
[code style=(.*)]text[/code]
,因此,例如,如果样式是PHP,则我想突出显示标签内的代码,以及其他语言。     

解决方法

为什么要重新发明轮子。 Stackoverflow已经对此有了答案:PHP语法突出显示 更新 看完评论。您可以像这样转换它:
<?php
function parseContent( $string )
{
    $search = \'/\\[code style=\"(.*?)\"\\](.*?)\\[\\/code\\]/is\';
    preg_match_all($search,$string,$output);

    foreach( $output[ 0 ] as $idx => $raw_html)
    {
        $style   = $output[ 1 ][ $idx ];
        $content = $output[ 2 ][ $idx ];

        $new_html = \"<div class=\'codetext\' id=\'$style\'>$content</div>\";
        $string = str_replace($raw_html,$new_html,$string);
    }

    return $string;
}
?>
这是一些测试代码:
<?php
$string = <<<EOM
some pre content
[code style=\"php\"]
<?php
    echo \"this is PHP\";
?>
[/code]
some content in the middle
[code style=\"html\"]
<body>
    <h1>TITLE IS HERE!</h1>
</body>
[/code]
another content after content
EOM;

$string = parseContent( $string );
?>