Is there a simple way to get no unnecessary block-level HTML output from PHP-markdown?
Comment *text* should yield Comment <em>text</em> instead of <p>Comment <em>text</em></p>
This way the output could easily be used in labels (in my case) or comments (like on SO).
There's no such configuration setting for the parser, but maybe I overlooked something or there's a fork for this. It seems like a fairly simple, often-needed feature.
Of course some syntax has to result in block-level elements, but it would be nice if that only happened when necessary/intended.
At the moment I catch the least necessary transformations like this:
$markdown = Markdown::defaultTransform($val);
if(substr_count($markdown,"</p>")===1 AND preg_match("@^<p>(.+)</p>$@",trim($markdown),$matches)):
$val = $matches[1];
else:
$val = $markdown;
endif;
I don’t know any good quick code for that, but you can contact Michel Fortin to implement this feature.
But, if you want taht quickly, you can create your own class that implements the original one and put some mathod to do what you want, so, one possible example could be the following:
<?php
include('Michelf/Markdown.php');
use \Michelf\Markdown;
/**
* Custom Markdown class
*
* This class has just one method yet, to do inline transform without some
* block HTML elements.
*/
class MyMarkdown extends Markdown
{
/**
* Does inline render, preventing use of `blockquote`, `p` and `hX` tags.
*
* @param string $str The Markdown string to transform
* @static
* @access public
* @return string HTML string
*/
public static function inlineTransform($str)
{
$htmlStr = trim(self::defaultTransform(trim($str)));
$arrMatches = array();
preg_match('@^<(h[1-6]{1}|p|blockquote)>(.+)</(h[1-6]|p|blockquote)>$@', $htmlStr, $arrMatches);
if(isset($arrMatches[2]))
{
return $arrMatches[2];
}
return $htmlStr;
}
}
// some examples
var_dump(Markdown::defaultTransform('My *text*'));
var_dump(MyMarkdown::inlineTransform('My *text*'));
var_dump(Markdown::defaultTransform('## My *text*'));
var_dump(MyMarkdown::inlineTransform('## My *text*'));
var_dump(Markdown::defaultTransform(' My *text*'));
var_dump(MyMarkdown::inlineTransform(' My *text*'));
Hope this can help you…
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With