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:

// 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";




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.

Follow us on Facebook and Twitter for latest update.