VOOZH about

URL: https://www.geeksforgeeks.org/php/remove-new-lines-from-string-in-php/

⇱ Remove new lines from string in PHP - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Remove new lines from string in PHP

Last Updated : 17 Jul, 2024

Given a multiple line sentence or statement the task is to convert the whole statement in a single line. See the example below. Examples:

Input : Hello
welcome to geeksforgeeks.
Output : Hello welcome to geeksforgeeks.
Remove the new line between Hello and geeksforgeeks.

Input : I
love
geeksforgeeks
Output : I love geeksforgeeks

Here are some common approaches

1. Using str_replace

You can use str_replace in PHP to replace newline characters with spaces or simply remove them to concatenate multiple lines into a single line.

Example:


Output
Hello 
welcome to 
geeksforgeeks
Hello welcome to geeksforgeeks 

2. Using preg_replace()

You can use preg_replace() in PHP to replace newline characters with spaces or simply remove them to concatenate multiple lines into a single line.

Example:


Output
I love geeksforgeeks

Using implode() and explode()

The explode() function splits a string by a specified delimiter, and the implode() function joins array elements into a single string using a specified delimiter.

Example


Output
Hello welcome to geeksforgeeks.
I love geeksforgeeks
Comment