如何将单个换行视为PHP Markdown中的实际换行符?

时间:2010-01-19 11:10:44

标签: php newline markdown

我正在阅读http://github.github.com/github-flavored-markdown/

我想在PHP Markdown中实现“Newline修改”:

我能想到的最好的是:

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

但这非常难以置信。

4 个答案:

答案 0 :(得分:14)

在降价文件中查找行:

function doHardBreaks($text) {

并从下面更改其下方的preg模式:

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

为:

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

或者你可以扩展markdown类,重新声明'doHardBreaks'函数,并将返回更改为类似上面的代码

此致,Achmad

答案 1 :(得分:1)

作为临时脚本,您可以在运行降价脚本之前在字符串上运行此脚本

$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);

基于github flavored markdown

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

P.S。我不是最好的正则表达式,我不知道github使用什么编程语言所以我即兴创作

答案 2 :(得分:0)

PHP的nl2br -function没有削减它?

nl2br - 在字符串中的所有换行符之前插入HTML换行符

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

如果你还想删除所有换行符(nl2br insert&lt; br /&gt;),你可以这样做:

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

如果没有,请详细说明您的解决方案如何失败,以及您想要解决的问题。

答案 3 :(得分:0)

我想出了以下解决方案,模仿gfm换行符的大部分内容。它通过了原帖中提到的页面上的所有相关测试。请注意,下面的代码会预处理 markdown 并输出风味降价。

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