php 新行到段落功能
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7409512/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
New line to paragraph function
提问by Jeremy
I have this interesting function that I'm using to create new lines into paragraphs. I'm using it instead of the nl2br()function, as it outputs better formatted text.
我有一个有趣的功能,我用它来在段落中创建新行。我使用它而不是nl2br()函数,因为它输出格式更好的文本。
function nl2p($string, $line_breaks = true, $xml = true) {
$string = str_replace(array('<p>', '</p>', '<br>', '<br />'), '', $string);
// It is conceivable that people might still want single line-breaks
// without breaking into a new paragraph.
if ($line_breaks == true)
return '<p>'.preg_replace(array("/([\n]{2,})/i", "/([^>])\n([^<])/i"), array("</p>\n<p>", '<br'.($xml == true ? ' /' : '').'>'), trim($string)).'</p>';
else
return '<p>'.preg_replace(
array("/([\n]{2,})/i", "/([\r\n]{3,})/i","/([^>])\n([^<])/i"),
array("</p>\n<p>", "</p>\n<p>", '<br'.($xml == true ? ' /' : '').'>'),
trim($string)).'</p>';
}
}
The problem is that whenever I try to create a single line break, it inadvertently removes the first character of the paragraph below it. I'm not familiar enough with regex to understand what is causing the problem.
问题是,每当我尝试创建单个换行符时,它都会无意中删除其下方段落的第一个字符。我对正则表达式不够熟悉,无法理解导致问题的原因。
回答by Laurent le Beau-Martin
The problem is with your match for single line breaks. It matches the last character before the line break and the first after. Then you replace the match with <br>, so you lose those characters as well. You need to keep them in the replacement.
问题在于您对单换行符的匹配。它匹配换行符之前的最后一个字符和之后的第一个字符。然后你用 替换匹配<br>,所以你也会丢失这些字符。您需要将它们保留在替换中。
Try this:
尝试这个:
function nl2p($string, $line_breaks = true, $xml = true) {
$string = str_replace(array('<p>', '</p>', '<br>', '<br />'), '', $string);
// It is conceivable that people might still want single line-breaks
// without breaking into a new paragraph.
if ($line_breaks == true)
return '<p>'.preg_replace(array("/([\n]{2,})/i", "/([^>])\n([^<])/i"), array("</p>\n<p>", '<br'.($xml == true ? ' /' : '').'>'), trim($string)).'</p>';
else
return '<p>'.preg_replace(
array("/([\n]{2,})/i", "/([\r\n]{3,})/i","/([^>])\n([^<])/i"),
array("</p>\n<p>", "</p>\n<p>", '<br'.($xml == true ? ' /' : '').'>'),
trim($string)).'</p>';
}
回答by Jonathan
Here is another approach that doesn't use regular expressions. Note, this function will remove any single line-breaks.
这是另一种不使用正则表达式的方法。请注意,此功能将删除任何单个换行符。
function nl2p($string)
{
$paragraphs = '';
foreach (explode("\n", $string) as $line) {
if (trim($line)) {
$paragraphs .= '<p>' . $line . '</p>';
}
}
return $paragraphs;
}
If you only need to do this once in your app and don't want to create a function, it can easily be done inline:
如果你只需要在你的应用程序中执行一次并且不想创建一个函数,它可以很容易地内联完成:
<?php foreach (explode("\n", $string) as $line): ?>
<?php if (trim($line)): ?>
<p><?=$line?></p>
<?php endif ?>
<?php endforeach ?>
回答by NaturalBornCamper
I also wrote a very simple version:
我还写了一个非常简单的版本:
function nl2p($text)
{
return '<p>'.str_replace(array("\r\n", "\r", "\n"), '</p><p>', $text).'</p>';
}
回答by Shoelaced
@Laurent's answer wasn't working for me - the elsestatement was doing what the $line_breaks == truestatement should have been doing, and it was making multiple line breaks into <br>tags, which PHP's native nl2br()already does.
@Laurent 的回答对我不起作用 - 该else语句正在做该$line_breaks == true语句应该做的事情,并且它正在将多个换行符分成<br>标签,PHP 的本机nl2br()已经这样做了。
Here's what I managed to get working with the expected behavior:
这是我设法使用预期行为的方法:
function nl2p( $string, $line_breaks = true, $xml = true ) {
// Remove current tags to avoid double-wrapping.
$string = str_replace( array( '<p>', '</p>', '<br>', '<br />' ), '', $string );
// Default: Use <br> for single line breaks, <p> for multiple line breaks.
if ( $line_breaks == true ) {
$string = '<p>' . preg_replace(
array( "/([\n]{2,})/i", "/([\r\n]{3,})/i", "/([^>])\n([^<])/i" ),
array( "</p>\n<p>", "</p>\n<p>", '<br' . ( $xml == true ? ' /' : '' ) . '>' ),
trim( $string ) ) . '</p>';
// Use <p> for all line breaks if $line_breaks is set to false.
} else {
$string = '<p>' . preg_replace(
array( "/([\n]{1,})/i", "/([\r]{1,})/i" ),
"</p>\n<p>",
trim( $string ) ) . '</p>';
}
// Remove empty paragraph tags.
$string = str_replace( '<p></p>', '', $string );
// Return string.
return $string;
}
回答by MrCarrot
Expanding upon @NaturalBornCamper's solution:
扩展@NaturalBornCamper 的解决方案:
function nl2p( $text, $class = '' ) {
$string = str_replace( array( "\r\n\r\n", "\n\n" ), '</p><p>', $text);
$string = str_replace( array( "\r\n", "\n" ), '<br />', $string);
return '<p' . ( $class ? ' class="' . $class . '"' : '' ) . '>' . $string . '</p>';
}
This takes care of both double line breaks by converting them to paragraphs, and single line breaks by converting them to <br />
这通过将它们转换为段落来处理双换行符,并通过将它们转换为单换行符来处理 <br />
回答by internet-nico
Here's an approach that comes with a reverse method to replace paragraphs back to regular line breaks and vice versa.
这是一种带有反向方法的方法,可将段落替换回常规换行符,反之亦然。
These are useful to use when building a form input. When saving a users input you may want to convert line breaks to paragraph tags, however when editing the text in a form, you may not want the user to see any html characters. Then we would replace the paragraphs back to line breaks.
这些在构建表单输入时很有用。保存用户输入时,您可能希望将换行符转换为段落标记,但是在表单中编辑文本时,您可能不希望用户看到任何 html 字符。然后我们将段落替换回换行符。
// This function will convert newlines to HTML paragraphs
// without paying attention to HTML tags. Feed it a raw string and it will
// simply return that string sectioned into HTML paragraphs
function nl2p($str) {
$arr=explode("\n",$str);
$out='';
for($i=0;$i<count($arr);$i++) {
if(strlen(trim($arr[$i]))>0)
$out.='<p>'.trim($arr[$i]).'</p>';
}
return $out;
}
// Return paragraph tags back to line breaks
function p2nl($str)
{
$str = preg_replace("/<p[^>]*?>/", "", $str);
$str = str_replace("</p>", "\r\n", $str);
return $str;
}
回答by Silent Helper
Just type this between your lines:
只需在你的两行之间输入:
echo '<br>';
This will give you a new line.
这会给你一条新线。

