Re: preg_match or not?

From: Date: Sun, 07 Jul 2002 06:49:49 +0000
Subject: Re: preg_match or not?
References: 1 2  Groups: php.general 
Request: Send a blank email to php-general+get-105938@lists.php.net to get a copy of this message
Thanks, thats hit the nail on the head, and my headache is a whole lot better! Steve Cc Zona wrote: > In article <3D27DB2F.B09F4102@netscape.net>, > oneeightone@netscape.net (Steve Fitzgerald) wrote: > > > I have been struggling for a couple of hours now trying to write a > > preg_match expression to validate a dollar amount - the user may or may > > not put in the decimals so I want to allow only digits plus a possible > > period followed by two more digits. My eyes are now swimming and I just > > can't seem to get right. This is what I have at the moment: > > > > if (!preg_match("/[\d]+([\.]{1}[\d]{2})?/", $form_data[amount])) // > > wrong amount > > > > but it still allows invalid input. Can anyone help or is there a better > > way to do it? > > It sounds like you need an exact match; note that your regex is matching > against substrings, thus additional invalid characters are allowed to pass. > Anchor the pattern, so that it essentially says "From beginning to end, the > only chars allowed are one or more digits, optionally followed by the > combination of a period then two more digits." (The "^" and "$" > special > chars are anchors.) > > A regex special character loses it "specialness" when it's either escaped > with a backslash, or included within a square-bracketed character class; > you don't need to do both. > > The {1} is implied; you don't need it. > > if (preg_match("/^\d+(\.\d{2})?$/", $form_data[amount])) > {echo "Validated!";} > else > {exit("That's not a dollar amount.");} > > -- > CC

« previous php.general (#105938) next »