新行< p>到php

enyaitl3  于 2023-02-11  发布在  PHP
关注(0)|答案(6)|浏览(250)

我目前有很多笑话在一个数据库中,是格式化与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函数,而不是转换成一个<p></p>,如果只有1 <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.

有人能给我指出正确的方向或者给予我一个简单的函数吗?谢谢

kmynzznz

kmynzznz1#

使用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>";
ia2d9nvy

ia2d9nvy2#

简单地直接转换原始字符串:

$text=str_replace("<br /><br />", "</p><p>", $original_string);

在HTML中,类似这样的地方:

<p>
 <?php echo $text; ?>
</p>
7z5jn7bk

7z5jn7bk3#

一句话:

$sNewString = implode('</p><p>',explode('<br /><br />', nl2br($sOriginalString)))

说明:
1.将换行符转换为br
1.通过这些br将字符串拆分为数组
1.通过在每个数组项之间粘贴P标签,将数组粘回到字符串

2w2cym1i

2w2cym1i4#

<?php
   function nl2p($string = '') {
        $array = explode("\n", $string);
        $content = '';
        foreach ($array as $str) {
            $content .= "<p>" . $str . "</p>";
        }
        return $content;
    }

回声nl 2 p($内容);

enxuqcxy

enxuqcxy5#

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

wsxa1bj16#

"试试看"

$old_string = preg_replace("/[\r\n]/","</p><p>",$old_string);
$new_string = "<p>" . $old_string . "</p>";
echo $new_string;

相关问题