简体   繁体   中英

Remove line breaks and add BR tags in PHP

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.

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

That should work, too: (though simplistic)

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

It was tested.

Either I'm missing something or no one gave the simplest solution possible -- built-in function nl2br :

echo nl2br($string);

Only remember, that if you're using pure string (not a variable) as nl2br 's argument, you must use double quotes or else your control characters, like \\n or \\r won't be expanded.

这对我来说

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM