PHP Regular Expression Exercises: Remove new lines from a string
5. Remove new lines (characters) from a string
Write a PHP script to remove new lines (characters) from a string.
Sample strings : "Twinkle, twinkle, little star,\nHow I wonder what you are.\nUp above the world so high,\nLike a diamond in the sky.";
Visual Presentation:

Sample Solution:
PHP Code:
<?php
// Original string containing multiple spaces and newlines
$str = "Twinkle, twinkle, little star,\nHow I wonder what you are.\nUp above the world so high,\nLike a diamond in the sky.";
// Using preg_replace to replace one or more consecutive spaces with a single space and removing leading/trailing spaces
echo preg_replace('/\s+/', ' ', trim($str))."\n";
?>
Output:
Twinkle, twinkle, little star, How I wonder what you are. Up above the world so high, Like a diamond in the sky.
Explanation:
In the exercise above,
This PHP code takes a string containing multiple spaces and newlines. It then uses a regular expression with "preg_replace()" to replace one or more consecutive spaces with a single space.
Additionally, "trim()" function is used to remove any leading or trailing spaces. Finally, it echoes the modified string.
Flowchart :

For more Practice: Solve these Related Problems:
- Write a PHP script to convert all line breaks in a multiline string into a single space while preserving paragraph breaks using double newlines.
- Write a PHP function to replace newlines in a string with HTML `
` tags for web display. - Write a PHP script to remove newlines only if they are followed by lowercase letters (e.g., soft-wrapped lines).
- Write a PHP function that collapses all newline and tab characters in a string into a single whitespace character.
Go to:
PREV : Remove nonnumeric characters except comma and dot.
NEXT : Extract text (within parenthesis) from a string.
PHP Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.