'default value' or 'fill-up' in RegEx?

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
tomcat007
Forum Newbie
Posts: 1
Joined: Thu Oct 30, 2008 3:54 am

'default value' or 'fill-up' in RegEx?

Post by tomcat007 »

Hi regex-gurus!

I´m getting crazy with a 'little' Problem in regex. All i want is a number which allows this Format "nn,nn"
So i made this regular expression: ([0-9][0-9])?,[0-9][0-9]

It works fine, but when the user just enters "12" then it should result in "12,00" so that he don´t always have to enter "00".
You understand what i mean?

How can i explain in regular expressions that the number should be filled up with "00" behind the "," if the user just entered 2 numbers?

Thanks for your help!
Greetings from Austria

Tom
User avatar
prometheuzz
Forum Regular
Posts: 779
Joined: Fri Apr 04, 2008 5:51 am

Re: 'default value' or 'fill-up' in RegEx?

Post by prometheuzz »

After validating the input, you can use the following regex to format your values:

Code: Select all

$value = preg_replace('/^(\d\d)$/', "$1,00", $value);
Although there probably is a built-in method in PHP for formatting (numerical) values, but the only thing I know is a bit of regex...
User avatar
GeertDD
Forum Contributor
Posts: 274
Joined: Sun Oct 22, 2006 1:47 am
Location: Belgium

Re: 'default value' or 'fill-up' in RegEx?

Post by GeertDD »

sprintf() should be able to handle this.
Post Reply