
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 in 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.
Advertisements