我有一个有趣的函数,用来在段落中创建新的行。我使用它而不是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>'; }
问题是,每当我尝试创建单行换行时,它都会无意中删除它下面段落的第一个字符。我对正则表达式不够熟悉,无法理解是什么导致了这个问题。
发布于 2011-09-14 07:10:01
问题出在单行换行的匹配上。它匹配换行前的最后一个字符和换行后的第一个字符。然后将匹配替换为<br>,因此也会丢失这些字符。你需要把它们放在替换品里。
试试这个:
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>", '$1<br'.($xml == true ? ' /' : '').'>$2'), 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>", '$1<br'.($xml == true ? ' /' : '').'>$2'),
trim($string)).'</p>';
}发布于 2013-01-23 04:32:35
这是另一种不使用正则表达式的方法。请注意,此函数将删除任何单个换行符。
function nl2p($string)
{
$paragraphs = '';
foreach (explode("\n", $string) as $line) {
if (trim($line)) {
$paragraphs .= '<p>' . $line . '</p>';
}
}
return $paragraphs;
}如果你只需要在你的应用程序中做一次,并且不想创建一个函数,它可以很容易地内联完成:
<?php foreach (explode("\n", $string) as $line): ?>
<?php if (trim($line)): ?>
<p><?=$line?></p>
<?php endif ?>
<?php endforeach ?>发布于 2016-03-10 12:49:25
我还写了一个非常简单的版本:
function nl2p($text)
{
return '<p>'.str_replace(array("\r\n", "\r", "\n"), '</p><p>', $text).'</p>';
}https://stackoverflow.com/questions/7409512
复制相似问题