简体   繁体   English

nl2br 表示段落

[英]nl2br for paragraphs

$variable = 'Afrikaans 
Shqip - Albanian  
Euskara - Basque';

How do I convert each new line to paragraph?如何将每个新行转换为段落?

$variable should become: $variable应该变成:

<p>Afrikaans</p>
<p>Shqip - Albanian</p>
<p>Euskara - Basque</p>

试试这个:

$variable = str_replace("\n", "</p>\n<p>", '<p>'.$variable.'</p>');

以下应该可以解决问题:

$variable = '<p>' . str_replace("\n", "</p><p>", $variable) . '</p>';

Be careful, with the other proposals, some line breaks are not catch.小心,对于其他建议,有些换行符没有被捕获。 This function works on Windows, Linux or MacOS :此功能适用于 Windows、Linux 或 MacOS:

function nl2p($txt){
    return str_replace(["\r\n", "\n\r", "\n", "\r"], '</p><p>', '<p>' . $txt . '</p>');
}
$array = explode("\n", $variable);
$newVariable = '<p>'.implode('</p><p>', $array).'</p>'
<?php
$variable = 'Afrikaans  
Shqip - Albanian   
Euskara - Basque'; 
$prep0 = str_replace(array("\r\n" , "\n\r") , "\n" , $variable);
$prep1 = str_replace("\r" , "\n" , $prep0);
$prep2 = preg_replace(array('/\n\s+/' , '/\s+\n/') , "\n" , trim($prep1));
$result = '<p>'.str_replace("\n", "</p>\n<p>", $prep2).'</p>'; 
echo $result;
/*
<p>Afrikaans</p>
<p>Shqip - Albanian</p>
<p>Euskara - Basque</p>
*/
?>

Explanation:说明:

$prep0 and $prep1: Make sure each line ends with \\n. $prep0 和 $prep1:确保每行都以 \\n 结尾。

$prep2: Remove redundant whitespace. $prep2:删除多余的空格。 Keep linebreaks.保持换行。

$result: Add p tags. $result: 添加 p 标签。

If you don't include $prep0, $prep1 and $prep2, $result will look like this:如果您不包括 $prep0、$prep1 和 $prep2,$result 将如下所示:

<p>Afrikaans  
</p>
<p>Shqip - Albanian   
</p>
<p>Euskara - Basque</p>

Not very nice, I think.不是很好,我想。

Also, don't use preg_replace unless you have to.另外,除非必须,否则不要使用 preg_replace。 In most cases, str_replace is faster (at least according to my experience).在大多数情况下, str_replace 更快(至少根据我的经验)。 See the comments below for more information.有关更多信息,请参阅下面的评论。

Try:尝试:

$variable = 'Afrikaans
Shqip - Albanian  
Euskara - Basque';

$result = preg_replace("/\r\n/", "<p>$1</p>", $variable);
echo $result;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM