w3resource

PHP Regular Expression Exercises: Remove the whitespaces from a string

PHP regular expression: Exercise-3 with Solution

Write a PHP script that removes the whitespaces from a string.

Sample string : 'The quick " " brown fox'

Visual Presentation:

PHP Regular Expression Exercise: Remove the whitespaces from a string

Sample Solution:

PHP Code:

<?php
// Define the input string
$str1 = 'The quick " " 	 brown fox';

// Use preg_replace function to remove all whitespace characters from the string
echo preg_replace('/\s+/', '', $str1)."\n";
?>

Output:

Thequick""brownfox

Explanation:

In the exercise above,

  • '$str1' variable stores the input string: 'The quick " " brown fox'.
  • The "preg_replace()" function performs regular expression-based string replacement.
  • The regular expression pattern /\s+/ is applied to the input string:
    • \s+: Matches one or more whitespace characters.
    • All matches for whitespace characters in the input string are replaced with an empty string, effectively removing them.
    • The modified string with all whitespace characters removed is then echoed.

    Flowchart :

    Flowchart: Remove the whitespaces 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 that removes the last word from a string.
    Next: Write a PHP script to remove nonnumeric characters except comma and dot.

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://w3resource.com/php-exercises/php-regular-expression-exercise-3.php