w3resource

PHP Regular Expression Exercises: Remove the whitespaces from a string


3. Remove whitespaces from a string

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

For more Practice: Solve these Related Problems:

  • Write a PHP function to remove all whitespaces from a string except those between quotation marks.
  • Write a PHP script to remove whitespaces only between alphabetic characters but preserve formatting within numbers and symbols.
  • Write a PHP function that removes all tabs, newlines, and double spaces from a string, compressing everything into a single line.
  • Write a PHP program to remove leading and trailing whitespaces from each line of a multi-line string and return the cleaned result.

Go to:


PREV : Remove the last word from a string.
NEXT : Remove nonnumeric characters except comma and dot.

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.



Follow us on Facebook and Twitter for latest update.