PHP Regular Expression Exercises: Remove new lines 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 :
PHP Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a PHP script to remove nonnumeric characters except comma and dot.
Next: Write a PHP script to extract text (within parenthesis) from a string.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics