PHP Regular Expression Exercises: Remove nonnumeric characters except comma and dot
PHP regular expression: Exercise-4 with Solution
Write a PHP script to remove nonnumeric characters except comma and dot.
Sample string : '$123,34.00A'
Visual Presentation:
Sample Solution:
PHP Code:
<?php
// Define a string containing alphanumeric characters, including special characters like comma and period.
$str1 = "$12,334.00A";
// Use preg_replace function to remove all characters except digits (0-9), comma (,), and period (.).
// The regular expression pattern "/[^0-9,.]/" matches any character that is not a digit, comma, or period.
// The replacement parameter is an empty string, effectively removing all non-digit, comma, and period characters.
echo preg_replace("/[^0-9,.]/", "", $str1)."\n";
?>
Output:
12,334.00
Explanation:
In the exercise above,
The given PHP code removes all characters except digits (0-9), comma (,), and period (.) from the string '$str1'.
It uses the 'preg_replace' function with a regular expression pattern '"/[^0-9,.]/"' to match any character that is not a digit, comma, or period, and replaces those characters with an empty string.
Finally, it echoes the modified string.
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 whitespaces from a string.
Next: Write a PHP script to remove new lines (characters) from a string.
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://w3resource.com/php-exercises/php-regular-expression-exercise-4.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics