开发者

PHP BBCode style code conversion using regex

So I have a tag like [code style=php]<?php echo "Hello world!"; ?>[/code]

A user may use plenty of those tags in a textarea so开发者_开发知识库 what I want to search for is [code style=(.*)]text[/code] so if the style is PHP for example I want to do highlight the code inside the tags and so on with other languages.


Why reinvent the wheel. Stackoverflow already has answer for this: PHP syntax highlighting

UPDATE

After reading comment. You can convert it like this:

<?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;
}
?>

Here's some test code:

<?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 );
?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜