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
<!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.