开发者

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

开发者 https://www.devze.com 2022-12-16 17:21 出处:网络
I was reading http://github.github.com/github-flavored-markdown/ I would like to implement that \"Newline modification\" in PHP Markdown:开发者_如何学Python

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

I would like to implement that "Newline modification" in PHP Markdown:开发者_如何学Python

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.


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


I've came up with the following solution, imitating most parts of the gfm newline behavior. It passes all the relevant tests on the page mentioned in the original post. Please note that the code below preprocesses markdown and outputs flavored markdown.

preg_replace('/(?<!\n)\n(?![\n\*\#\-])/', "  \n", $content);


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


PHP's nl2br -function doesn't cut it?

nl2br — Inserts HTML line breaks before all newlines in a string

http://php.net/manual/en/function.nl2br.php

If you also want to remove all linebreaks (nl2br inserts <br/>), you could do:

str_replace('\n', '', nl2br($my_html));

If not, please elaborate on how your solution fails, and what you'd like to fix.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号