tags:

views:

175

answers:

3

I am have completed javascript validation of a form using Regular Expressions and am now working on redundant verification server-side using PHP.

I have copied this regular expression from my jscript code that finds dollar values, and reformed it to a PHP friendly format:

/\$?((\d{1,3}(,\d{3})*)|(\d+))(\.\d{2})?$/

Specifically:

if (preg_match("/\$?((\d{1,3}(,\d{3})*)|(\d+))(\.\d{2})?$/", $_POST["cost"])){}

While the expression works great in javascript I get :

Warning: preg_match() [function.preg-match]: Compilation failed: nothing to repeat at offset 1

when I run it in PHP. Anyone have a clue why this error is coming up?

A: 

From PHP documentation:

Do not use preg_match() if you only want to check if one string is contained in another string. Use strpos() or strstr() instead as they will be faster.

bancer
How is that relevant? The OP is doing a regex match, and the `preg_*` functions are how you do that.
Alan Moore
Yeah, I'm testing a format not a string or I would avoid regex like the plague.
Thildemar
+1  A: 

Try this:

if (preg_match('/\$?((\d{1,3}(,\d{3})*)|(\d+))(\.\d{2})?$/', $_POST["cost"])){}

The dollar sign between " are considered as the start of a variable. Compare with these two code snippets:

1:

$var = "hello";
echo "$var world";

2:

$var = "hello";
echo '$var world';
Emil Vikström
Also true, thanks!
Thildemar
A: 

you have to double escape the $.

if (preg_match("/\\\$?((\d{1,3}(,\d{3})*)|(\d+))(\.\d{2})?$/", $_POST["cost"])){}

just putting \$ will have php escape the $ from starting a variable. You also have to add another escaped \ (\\) in front. Or you could just use single quotes so php doesn't interpret the $ as the start of a variable.

Jonathan Kuhn
Works great, I hate swapping languages and forgetting all of the escaped characters =(. Thanks!
Thildemar