Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to treat single newline as real line break in PHP Markdown?

I was reading http://github.github.com/github-flavored-markdown/

I would like to implement that "Newline modification" in PHP Markdown:

Best I could think of is:

$my_html = Markdown($my_text);
$my_html = preg_replace("/\n{1}/", "<br/>", $my_html);

But this runs very unexpectable.

like image 229
Lauri Avatar asked Jan 19 '10 11:01

Lauri


2 Answers

Look for line in your markdown file:

function doHardBreaks($text) {

and change the preg pattern below it from:

return preg_replace_callback('/ {2,}\n/', array(&$this, '_doHardBreaks_callback'), $text);

to:

return preg_replace_callback('/ {2,}\n|\n{1}/', array(&$this, '_doHardBreaks_callback'), $text);

Or you can just extend the markdown class, redeclare 'doHardBreaks' function, and change the return into something like code above

Regards, Achmad

like image 179
adods Avatar answered Nov 11 '22 20:11

adods


As an ad-hoc script you can just run this on your string before running the markdown script

$text = preg_replace_callback("/^[\w\<][^\n]*\n+/msU",function($x){
$x = $x[0];
$x = preg_match("/\n{2}/",$x,$match)? $x: trim($x)."  \r\n";
return $x;
},$text);

$my_html = Markdown($text);

Based on the github flavored markdown

text.gsub!(/^[\w\<][^\n]*\n+/) do |x|
    x =~ /\n{2}/ ? x : (x.strip!; x << "  \n")
end

P.S. I'm not the best at regex and I don't know what programming language github uses so I improvised

like image 26
Timo Huovinen Avatar answered Nov 11 '22 19:11

Timo Huovinen