Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Remove new lines from a string and replace with one empty space PHP?
In PHP, you can remove newlines from a string and replace them with spaces using several methods. The most common approaches are using preg_replace(), str_replace(), or trim() combined with regular expressions.
Problem Example
Consider this string with newlines ?
$sentence = " My name is John Smith My Favorite subject is PHP. ";
We need to remove the newlines and replace them with single spaces to get ?
My name is John Smith My Favorite subject is PHP.
Method 1: Using preg_replace() with trim()
This method uses regular expressions to replace multiple whitespace characters (including newlines) with a single space ?
<?php
$sentence = "
My name is John Smith
My Favorite subject is PHP.
";
$sentence = trim(preg_replace('/\s\s+/', ' ', $sentence));
echo $sentence;
?>
My name is John Smith My Favorite subject is PHP.
Method 2: Using str_replace()
A simpler approach using str_replace() to target specific newline characters ?
<?php $sentence = " My name is John Smith My Favorite subject is PHP. "; $sentence = trim(str_replace(["\r<br>", "\r", "<br>"], ' ', $sentence)); echo $sentence; ?>
My name is John Smith My Favorite subject is PHP.
Method 3: Using preg_replace() for All Whitespace
This method replaces any whitespace sequence (newlines, tabs, multiple spaces) with a single space ?
<?php
$sentence = "
My name is John Smith
My Favorite subject is PHP.
";
$sentence = trim(preg_replace('/\s+/', ' ', $sentence));
echo $sentence;
?>
My name is John Smith My Favorite subject is PHP.
Comparison
| Method | Performance | Handles Multiple Spaces |
|---|---|---|
str_replace() |
Fastest | No |
preg_replace('/\s+/', ' ') |
Moderate | Yes |
preg_replace('/\s\s+/', ' ') |
Moderate | Yes |
Conclusion
Use str_replace() for simple newline removal or preg_replace() when you need to handle multiple whitespace characters. Always use trim() to remove leading and trailing spaces.
