I'm currently working on a project in PHP and I'm in need of some Regex help. I'd like to be able to take a user inputted monetary value and strip all non numeric and decimal places/cents.
Ex:
'2.000,00' to '2000'
'$ 2.000,00' to '2000'
'2abc000' to '2000'
'2.000' to 2000
(I'm using non US currency formatting)
How can I do this? I'd appreciate the help - Thanks
In order to remove all non-numeric characters from a string, replace() function is used. replace() Function: This function searches a string for a specific value, or a RegExp, and returns a new string where the replacement is done.
The idea is to use String. replaceAll() method that replaces all the sequence of characters that matches the given Regular Expression with the given replacement string.
The approach is to use the String. replaceAll method to replace all the non-alphanumeric characters with an empty string.
sub() method to remove all non-numeric characters from a string, e.g. result = re. sub(r'[^0-9]', '', my_str) . The re. sub() method will remove all non-numeric characters from the string by replacing them with empty strings.
You can do:
$str = preg_replace('/[^0-9,]|,[0-9]*$/','',$str);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With