Dylan Cross
Dylan Cross

Reputation: 5986

preg_match(): Compilation failed: nothing to repeat at offset 2

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

Upvotes: 1

Views: 13168

Answers (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

Upvotes: 2

Barmar
Barmar

Reputation: 782508

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);

Upvotes: 4

Related Questions