tags:

views:

146

answers:

3

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

So this -

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 become this -

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 highlighting of any letters.

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

The above replaces double-newlines with the <br/> tag and any left-over single newlines into a space (to avoid words originally only separated by a newline from running into one another).

Would you have any need to cater for CRLF (windows) style line breaks; that would slightly (though not drastically) change the approach.

salathe
this seems right also, but I figured you can't tell if on the empty line there's a space or not, or if there are any \r chars
Gabriel Poama-Neagra
@Gabriel: absolutely, we can only do the best with what the question-asker gives us.
salathe
+5  A: 

well, it seems that you consider a paragraph delimiter, an empty line. So the easiest solution seems this:

$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. $textResult would have your result

Gabriel Poama-Neagra
+1 Ah finally, someone with some sense! I haven't tested so it better work otherwise I'll be back!
zaf
+2  A: 

That should work, too: (though simplistic)

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

It was tested.

Best regards,
T.

Thiago Silveira