使用php关闭标记后添加换行符或换行符

I have this text in a MySql database:

First paragraph very long.
Second paragraph very long.
Third paragraph.

I add p tags and it works:

$text = preg_replace("/
/","<p>",$text);
$text = '<p>'.$text;

I try to add line breaks when I echo to a html page. I tried 3 different things. But none of them seem to work:

$text = preg_replace("/<\/p>/","</p>

",$text);
$text = preg_replace("/<\/p>/","</p><br><br>",$text);
$text = nl2br($text);
echo $text;

If I go to the web inspector in the Safari browser, I get this:

<p>First paragraph very long.</p><p>Second paragraph very long.</p><p>Third paragraph.</p>

I would like to have this:

<p>First paragraph very long.</p>
>

<p>Second paragraph very long.</p>
>

<p>Third paragraph.</p>
>

It seems that my regex does not select <\/p> even when I escape it. I do not understand. What is wrong?

Presuming you need newline control chars (and not html line break tags):

$text = "First paragraph very long.
Second paragraph very long.
Third paragraph.";
$text = '<p>' . preg_replace("~
~", "<p>

</p>", trim($text)) . '</p>;

Note trim is used incase you have leading or trailing newlines, ~ is used as a delimiter, because / is a poor choice when dealing with html, causeing you to escape all over the place.

It is not apparent in the above example, but using some of your reqex as an example:

preg_replace("~</p>~","</p>

",$text);

is much easier to read than:

preg_replace("/<\/p>/","</p>

",$text);

Also, you dont need regex, you could just use str_replace:

$text = '<p>' .str_replace("
", "<p>

</p>", trim($text)) . '</p>;

Or even explode/implode:

$text = '<p>' . implode("</p>

<p>", explode("
", trim($text))) . '</p>';

If it was html line breaks you wanted, then you could just edit the replacement argument to:

"</p><br><br><p>"

in any of the above, but it would probably be better to use some css:

p{
    margin-bottom:10px;
}

You don't need regex, simple str_replace works (in your example):

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