Remove line breaks and add BR tags in PHP

I have the following text for which I would like to add a tag <br>between each paragraph. And also remove all line breaks. How do I do this in PHP? Thank.

So this is -

This is some text
for which I would
like to remove 
the line breaks.

And I would also 
like to place
a b>  tag after 
every paragraph.

Here is one more
paragraph.

Would it be -

This is some text for which I would like to remove the line breaks.<br/> And I would also like to place a br tag after every paragraph. <br> Here is one more paragraph.

NOTE. Ignore the selection of any letters.

+3
source share
5 answers

This should work too: (albeit simplified)

$string = str_replace("\n\n", "<br />", $string);
$string = str_replace("\n", "", $string);

It has been tested.

+5
source

Well, it seems that you are considering a paragraph separator, an empty line. Thus, the simplest solution is as follows:

$text  = str_replace( "\r", "", $text ); // this removes the unwanted \r
$lines = explode( "\n", $text ); // split text into lines.
$textResult = "";
foreach( $lines AS $line )
{
   if( trim( $line ) == "" ) $textResult .= "<br />";
   $textResult .= " " . $line;
}

I think this solves your problem. $textResultwill have your result

+7
source

- , - nl2br:

echo nl2br($string);

, ( ) nl2br, , , \n \r, .

+3
echo str_replace(array("\n\n", "\n"), array("<br/>", " "), $subject);

<br/> ( , , ).

CRLF (); ( ) .

0

$string = ereg_replace( "\n", "<br/>", $string); >

0

Source: https://habr.com/ru/post/1744981/


All Articles