views:

166

answers:

2

Hi

I am trying to use the following regular expression to check whether a string is a positive number with either zero decimal places, or 2:

^\d+(\.(\d{2}))?$

When I try to match this using preg_match, I get the error:

Warning: preg_match(): No ending delimiter '^' found in /Library/WebServer/Documents/lib/forms.php on line 862

What am I doing wrong?

+1  A: 

For PHP's preg suite of functions, the regexes must be specified with a delimiter, such as /; for instance, /[a-z]/ will match any character from a to z. When you give it the string "^\\d+(.(\\d{2}))?$", it wants to treat the regex as \\d+(.(\\d{2}))?$, delimited by ^s, but it can't find the second ^. Thus, fixing that is as simple as "/^\\d+(.(\\d{2}))?$/" The other thing you need to fix is the .; that's a metacharacter which will match any non-newline character; for a literal period, you want \.. This gives you the regex "/^\d+(\.(\d{2}))?$/". Also, note that if you don't want a capturing group, you can use "/^\d+(?:\.(\d{2}))?$/", which will put the digits after the decimal point in $1 instead of $2.

Antal S-Z
+2  A: 

The error is about delimiter missing that is / or #, etc, make sure that you wrap regex expression in delimiters:

if (preg_match('/^\d+(\.(\d{2}))?$/'), $text)
{
 // more code
}

Or:

if (preg_match('#^\d+(\.(\d{2}))?$#'), $text)
{
 // more code
}
Sarfraz
Delimiters are not limited to `/` and `#`, you can use any non-alphanumeric (excluding whitespace and backslash) e.g. `*`, `@`, `|`, `!`,..... are all valid delimiters.
nico
@nico: That's useful addition. Thanks
Sarfraz
@Sarraz Ahmed: No prob! It's good to know, because the time you're actually searching for `some weird /#/ string` (hey, you'll never know!) you may find it easier to use `!` as a delimiter!! :)
nico