Skip to content

Instantly share code, notes, and snippets.

@pjdietz
Last active December 21, 2015 22:09
Show Gist options
  • Save pjdietz/6373043 to your computer and use it in GitHub Desktop.
Save pjdietz/6373043 to your computer and use it in GitHub Desktop.
Convert GFM-style codeblocks to HTML for use with SyntaxHighlighter (http://alexgorbatchev.com/SyntaxHighlighter/)
<?php
/**
* Convert GFM-style code blocks to HTML for use with SyntaxHighlighter
*
* @param string $text
* @return string
*/
function fencedCodeBlocksToHtml($text)
{
$regex = <<<'REGEX'
{
# \1: Opening marker. Three of more tildes of backticks.
(
~{3,}|`{3,}
)
# \2: Rest of the line.
(.*)$\n
# \3: Content
(
(?>
(?!\1 [ ]* \n) # Not a closing marker.
.*\n+
)+
)
# Closing marker.
\1
}xm
REGEX;
$callback = function ($matches) {
return sprintf('<pre class="brush: %s">%s</pre>',
$matches[2],
htmlspecialchars($matches[3])
);
};
return preg_replace_callback($regex, $callback, $text);
}
/*
Example: Turns this...
```php first-line: 10; highlight: [2, 4, 6]
print "<h1>Hello, world!</h1>";
```
...into this...
<pre class="brush: php first-line: 10; highlight: [2, 4, 6]">print &quot;&lt;h1&gt;Hello, world!&lt;/h1&gt;&quot;;</pre>
You'll still need to run the resulting string through a function to convert the
rest of the Markdown, but the code blocks will be HTML and should be ignored.
If you're not using SyntaxHighlighter, modify the callback to produce
whatever HTML you need.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment