- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
<!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.
- Related Articles
- Remove new lines from string in PHP
- How to remove empty string/lines from PowerShell?
- How to Remove Empty Lines from a File on ubuntu
- Remove newline, space and tab characters from a string in Java
- Java Program to replace all occurrences of given String with new one
- Java Program to replace only first occurrences of given String with new one
- Remove comma from a string in PHP?
- Python Program to Take in a String and Replace Every Blank Space with Hyphen
- Remove the whitespaces from a string using replace() in JavaScript?
- How to remove an empty string from a list of empty strings in C#?
- Replace All Occurrences of a Python Substring with a New String?
- How to remove a character (‘’) in string array and display result in one string php?
- Replace one string with another string with Java Regular Expressions
- How can I remove all empty values when I explode a string using PHP?
- Replace the empty values from a MySQL table with a specific value

Advertisements