w3resource

PHP Regular Expression Exercises: Remove new lines from a string

PHP regular expression: Exercise-5 with Solution

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:

PHP Regular Expression Exercise: Remove new lines from a string

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 :

Flowchart: Remove new lines from a string

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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/php-exercises/php-regular-expression-exercise-5.php