lIP TT lIP TT - 3 months ago 10
PHP Question

PHP remove black new lines

I have got this php code

$Text=htmlspecialchars($_POST['new_post'],ENT_QUOTES);
$Text=trim($Text);


Text
is variable that is defined by user.If
text
is

There is a pleasure in the pathless woods,
There is a rapture on the lonely shore,
There is society, where none intrudes.


I want it to stay like that.But if
Text
is

By the deep Sea, and music in its roar:


I love not Man the less, but Nature more,



From these our interviews, in which I steal


I want it to be

By the deep Sea, and music in its roar:
I love not Man the less, but Nature more,
From these our interviews, in which I steal


How can i achieve that with PHP?

Answer

A simple solution would be to use preg_replace(). This will find any multiple lines, and replace them with a single new line:

$Text = preg_replace("/[\r\n]+/", "\n", $Text);

See a demo here:

$Text = "There is a pleasure in the pathless woods,


There is a rapture on the lonely shore,


There is society, where none intrudes.";


$Text=trim($Text);
$Text=preg_replace("/[\r\n]+/", "\n", $Text);

echo $Text;