PHP code to convert text blocks indented by four spaces into a <pre><code> block [Markdown]
I'm not very good at PHP and would like to have a PHP function which turns this (text block indented by four spaces):
printf("goodbye world!"); /* his suicide note
was in C */
Into this:
<pre><code> 开发者_JAVA技巧printf("goodbye world!"); /* his suicide note
was in C */</code></pre>
Leaving all other lines intact.
This is what Markdown does. I found this PHP port of Markdown (see function doCodeBlocks()
), but I don't want to use the entire Markdown file, I just want this one function.
Can someone provide me with the minimal PHP code required to get this to work? So I can do this:
<?php echo markdownPre('Here goes some code:
var x = 1, y = 2;
alert(x + y);
That should be a pre block.'); ?>
I have not tried, but I think you can preg_replace
the regex
/((?:^(?: {4}|\t).*$\n+)+)/m
with <pre><code>$1</code></pre>
.
Although Kenny's expression works, i'd suggest replacing with callback for flexibility:
function markdownPre($in) {
if(is_array($in)) {
$code = $in[0];
// post-process the code, e.g. remove leading spaces
$code = preg_replace('~^(\x20{4}|\t)~m', '', $code);
return "<pre>$code</pre>";
}
return preg_replace_callback('~(
^
(\x20{4} | \t)
(.+)
\n
)+~mx', __FUNCTION__, $in);
}
In the "post-process" phase you can do interesting things, for example, syntax highlighting.
I don't understand the problem correctly. Do you want something like -
function markdownPre($str){ return '< pre>< code>'.$str.''; }
this will return
<pre><code> printf("goodbye world!"); /* his suicide note
was in C */</code></pre>
if you pass
echo markdownPre('printf("goodbye world!"); /* his suicide note was in C */')
to it.
精彩评论