我目前在数据库中有很多笑话,这些笑话是用nl2br()格式生成的......
This is just dummy text. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
<br /><br />
Vestibulum gravida justo in arcu mattis lacinia. Mauris aliquet mi quis diam euismod blandit ultricies ac lacus.
<br /><br />
Aliquam erat volutpat. Donec sed nisi ac velit viverra hendrerit.
<br />
Praesent molestie augue ligula, quis accumsan libero.
我需要一个PHP函数,而不是将<br /><br />
转换为<p></p>
,如果只有<br />
,那么请不要管它。还修剪任何空格
所以最终的结果是......
<p>This is just dummy text. Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
<p>Vestibulum gravida justo in arcu mattis lacinia. Mauris aliquet mi quis diam euismod blandit ultricies ac lacus. </p>
Aliquam erat volutpat. Donec sed nisi ac velit viverra hendrerit.<br />
Praesent molestie augue ligula, quis accumsan libero.
有人能指出我正确的方向还是给我一个简单的功能呢?感谢
答案 0 :(得分:4)
使用PHP的字符串替换功能将所有<br /><br />
替换为</p><p>
。 http://php.net/manual/en/function.str-replace.php
示例代码:
$stringWithBRs = nl2br($originalString)
$stringWithPs = str_replace("<br /><br />", "</p>\n<p>", $stringWithBRs);
$stringWithPs = "<p>" . $stringWithPs . "</p>";
或者,您甚至无需调用nl2br()函数即可使用以下代码。
$stringWithPs = str_replace("\n\n", "</p>\n<p>", $originalString);
$stringWithPs = "<p>" . $stringWithPs . "</p>";
答案 1 :(得分:3)
只需直接转换原始字符串:
$text=str_replace("<br /><br />", "</p><p>", $original_string);
在HTML中,在这样的地方:
<p>
<?php echo $text; ?>
</p>
答案 2 :(得分:2)
单行:
$sNewString = implode('</p><p>',explode('<br /><br />', nl2br($sOriginalString)))
说明:
答案 3 :(得分:0)
$new = '';
foreach(explode("\n<br /><br />\n", $text) as $p) // split by double newlines
$new.= "<p>$p</p>\n"; // and convert each part to a paragraph
// or if you want to keep it in a single line
$new = join(array_map(function($p){return "<p>$p</p>\n";}, explode("\n<br /><br />\n", $text)));
答案 4 :(得分:0)
Try it
$old_string = preg_replace("/[\r\n]/","</p><p>",$old_string);
$new_string = "<p>" . $old_string . "</p>";
echo $new_string;