Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex - Strip non numeric and remove cents if any

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

like image 630
RS7 Avatar asked Jan 13 '11 01:01

RS7


People also ask

How do I remove non-numeric characters from a string?

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.

How do I remove a character from a number string?

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.

How do you remove non-numeric characters in Java?

The approach is to use the String. replaceAll method to replace all the non-alphanumeric characters with an empty string.

How do you remove non integers from a string in Python?

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.


1 Answers

You can do:

$str = preg_replace('/[^0-9,]|,[0-9]*$/','',$str); 
like image 134
codaddict Avatar answered Oct 11 '22 15:10

codaddict