PHP Regular Expression Exercises: Remove nonnumeric characters except comma and dot
4. Remove nonnumeric characters except comma and dot
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 :

For more Practice: Solve these Related Problems:
- Write a PHP function that extracts a valid monetary value from a mixed-character string preserving comma as thousand separator and dot as decimal.
- Write a PHP script to remove all nonnumeric characters from a string except dots, commas, and minus signs (for negative numbers).
- Write a PHP script that removes all characters except digits, commas, and dots, then validates the result as a proper floating-point number.
- Write a PHP function to clean up a string by removing all non-digits, while preserving one comma for thousands and one dot for decimal position.
Go to:
PREV : Remove whitespaces from a string.
NEXT : Remove new lines (characters) from a string.
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.