0

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.

1 Answer 1

0

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 );
?>
Sign up to request clarification or add additional context in comments.

2 Comments

as i see there is a javascript highlighter, but what i trully want is to make it inside in PHP, because the users use [code style=php]php code[/code] or c,java,c++ and so on this then gets replaced with a preg_replace function to div so it will create the CODE container and put inside the code text... the problem is how i will check for each code tag inside an article and replace each code tag with the proper highlight colors...
Im using this for now: $search = array( '/[code style=(.*?)](.*?)[\/code]/is' ); $replace = array( '<div class="codetext" id="$1">$2</div>' ); return preg_replace($search,$replace,$input); so if style = php and inside the code tags i have <?php echo "test"; ?> it will output <div class="codetext" id="php"><?php echo "test"; ?></div> how can i check what $1 is in order to highlight the $2 properly ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.