Regex - Strip non numeric and remove cents if any
16,362
Solution 1
You can do:
$str = preg_replace('/[^0-9,]|,[0-9]*$/','',$str);
Solution 2
$output = preg_replace('/[^0-9]/s', '', $input);
that should replace non numeric chars with empty strings.
Author by
RS7
Updated on July 28, 2022Comments
-
RS7 almost 2 years
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
-
RS7 over 13 yearsHow would I remove the cents? So that 2.000,00 doesn't become 200000?
-
Hoàng Long over 13 years@RS7: before doing what dqhendricks shows, you just need to get "strpos" of the comma (,), then get substring to that position.
-
dqhendricks over 13 yearspreg_replace('/,.+$/s', '', $input)
-
dqhendricks over 13 yearsor substr($input, 0, strrpos($input, ','))
-
dqhendricks over 13 yearsyou can even put the regexs into an array and do one preg_replace() statement to do both replacements.
-
dqhendricks over 13 years$output = preg_replace(array('/,.+$/s', '/[^0-9]/s'), '', $input);
-
Lightness Races in Orbit over 13 yearsI think that this question is much better answered as "cast to int or summat".
-
dqhendricks over 13 years@Tomalak Geret'kal No, because in the case of '2abc000', it would evaluate to 2 instead of 2000.
-
Lightness Races in Orbit over 13 years@dqhendricks: After applying the regex, I mean. I was referring to the followup question from RS7. Of course you can't just throw a single int cast and be done with it: the end solution would be more complex than that.
-
dqhendricks over 13 years@Tomalak Geret'kal good point. although I'm not sure how PHP handles type conversion for non-US decimals (',' as decimal marker instead of '.'). maybe there is a config setting.
-
Lightness Races in Orbit over 13 years@dqhendricks: I'm also note sure how strictly it follows locales (if at all). I'd imagine it's configurable somewhere.