Remove new lines from string in PHP
Last Updated :
17 Jul, 2024
Improve
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
Table of Content
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:
<?php
$text = "Hello \nwelcome to \ngeeksforgeeks";
echo $text;
echo "\n";
$text = str_replace("\n", "", $text);
echo $text;
?>
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:
<?php
$input = "I\nlove\ngeeksforgeeks";
// Replace newlines with spaces using preg_replace()
$output = preg_replace('/\s+/', ' ', $input);
echo $output; // Output: "I love geeksforgeeks"
?>
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
<?php
// Function to convert multiline string to a single line
function multilineToSingleLine($input) {
// Split the input string into an array using newline characters as delimiters
$lines = explode(PHP_EOL, $input);
// Join the array elements into a single string with spaces
$singleLine = implode(' ', $lines);
// Return the single-line string
return $singleLine;
}
$input1 = "Hello\nwelcome to geeksforgeeks.";
$input2 = "I\nlove\ngeeksforgeeks";
echo multilineToSingleLine($input1) . "\n";
echo multilineToSingleLine($input2) . "\n";
?>
Output
Hello welcome to geeksforgeeks. I love geeksforgeeks