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:
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 :
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.
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-3.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics