Jump to content

Recommended Posts

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

?>
Edited by PaulRyan
Link to comment
https://forums.phpfreaks.com/topic/276321-optimizing-code-parsing-function/
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.