1

I can't figure out why my regular expression is breaking.

I want it to match:

$100,000

100,000

100000 (I know it doesn't match this, but I want it to)

preg_match("/^\$?(?!0.00)\d{1,3}(,\d{3})*(\.\d\d)?$/", $string);

So how can I make it match the last one too, and why am i getting this error? This regular expression works fine in my javascript check.

Thanks

Dylan Cross
  • 5,918
  • 22
  • 77
  • 118

2 Answers2

4

You need to escape the backslash to make it literal, because it's escaping the dollar sign as part of PHP string syntax.

preg_match("/^\\\$?(?!0.00)\d{1,3}(,\d{3})*(\.\d\d)?$/", $string);

or use single quotes rather than double quotes:

preg_match('/^\$?(?!0.00)\d{1,3}(,\d{3})*(\.\d\d)?$/', $string);

To allow numbers without commas, you can use alternation:

preg_match('/^\$?(?!0.00)(\d{1,3}(,\d{3})*|\d+)(\.\d\d)?$/', $string);
Barmar
  • 741,623
  • 53
  • 500
  • 612
2

Add two slashes

preg_match("/^\\\$?(?!0.00)\d{1,3}(,\d{3})*(\.\d\d)?$/", $string,$matches);
               ^^

The code

<?php
$string='$100,000';
preg_match("/^\\\$?(?!0.00)\d{1,3}(,\d{3})*(\.\d\d)?$/", $string,$matches);
print_r($matches);

OUTPUT :

Array
(
    [0] => $100,000
    [1] => ,000
)

Update: If you want to match the numbers like 1, 1000, etc Then use below one, and notice the change:

preg_match("/^\\\$?(?!0.00)\d{1,3}(\,?\d{3})*(\.\d\d)?$/", $string,$matches);
                                     ^ here making the comma optional
Sabuj Hassan
  • 38,281
  • 14
  • 75
  • 85
Shankar Narayana Damodaran
  • 68,075
  • 43
  • 96
  • 126