Remove new lines from a string and replace with one empty space PHP?


Let’s say the following is our string with new line 

$sentence = "
My name is John Smith
My Favorite subject is PHP.
";

We need to remove the new line above and replace with a whitespace i.e. the output should be −

My name is John Smith My Favourite subject is PHP.

For this, use trim() and withing that preg_replace() to replace.

Example

The PHP code is as follows

 Live Demo

<!DOCTYPE html>
<html>
<body>
<?php
$sentence = "
My name is John Smith
My Favorite subject is PHP.
";
$sentence = trim(preg_replace('/\s\s+/', ' ', $sentence));
echo $sentence;
?>
</body>
</html>

Output

This will produce the following output

My name is John Smith My Favorite subject is PHP.

Updated on: 13-Oct-2020

563 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements