PaulRyan Posted March 30, 2013 Share Posted March 30, 2013 I have created a function to parse code blocks within my blog posts, it took me a little while to get my head around a few things, but I've completed it nonetheless.I would like to know if anyone can spot and functions I should be using, or ways of shortening the code down (without making things to complicated) or if anyone has a better function to do the same job. PLEASE NOTE!! I had to add backslashes the my own code blocks within my $blogPost so I could post it on here without breaking the code parser. <style> .codeBlock{ background: #FAFAFA; padding: 3px 5px; border: 1px solid #CCC; margin-top: 15px; } .lineNumber{ color: #444; } </style> <?PHP //### Example blog post content $blogPost = 'Testing my PHP code display/heightlighting parsing function.' .PHP_EOL; $blogPost .= '4cb09423dfa8b96afcf98c9361927b7a'), '', htmlentities($blogPost)); //### Iterate over all code blocks and replace markers with code block foreach($matches[1] AS $key => $codeBlock) { //### Highlight code string $codeBlock = highlight_string($codeBlock, TRUE); //### Remove the line endings from top and bottom of code block $codeBlock = preg_replace('#'.PHP_EOL.'#', '', $codeBlock); //### Explode the lines, so we can add line numbers $codeLines = explode('<br />', $codeBlock); //### Start output with code tag, to fix first line number error (shows as plain text) $codeBlockLines = '<code>'; //### Iterate over the code lines and add the line number with the line of code foreach($codeLines AS $line => $code) { $codeBlockLines .= '<span class="lineNumber">'. $line. ' |</span> '.$code . PHP_EOL; } //### Finally replace the code block back into the blog post $blogPost = str_replace('[?CODEBLOCK '.$key.'?]', '<div class="codeBlock">'. $codeBlockLines .'</div>', $blogPost); } //### Create new lines with output return nl2br($blogPost); } echo blog_post_parse($blogPost); ?> Link to comment https://forums.phpfreaks.com/topic/276321-optimizing-code-parsing-function/ Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.