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

前端 未结 4 1689
说谎
说谎 2021-02-06 01:44

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

相关标签:
4条回答
  • 2021-02-06 02:21

    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

    0 讨论(0)
  • 2021-02-06 02:21

    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);
    
    0 讨论(0)
  • 2021-02-06 02:26

    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

    0 讨论(0)
  • 2021-02-06 02:31

    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 讨论(0)
提交回复
热议问题