ReynierPM
ReynierPM

Reputation: 18660

Why this regular expression doesn't validate

I'm building a regular expression for check strings like G20003030 or like G-20003030. The first letter can be any of this: VGJ. This is my code:

$string = "G20003030";
if (preg_match('^[VGJ]{1,1}?[0-9]{8,8}$/', $string)) {
    echo "passed";
} else {
    echo "not passed";
}

But all the time it returns "not passed". What's wrong in my regular expression and how to check both variants? (I think my code only works for the first one)

Upvotes: 2

Views: 52

Answers (2)

driangle
driangle

Reputation: 11779

try using this regex:

/^[VGJ]-?[0-9]{8}$/

Upvotes: 2

Florent
Florent

Reputation: 12420

Warning: preg_match(): No ending delimiter '^' found in /code/xxxxxx.php on line 3

You forgot the first slash and the hyphen (thanks @Sepster).

/^[VGJ]-?[0-9]{8}$/

Upvotes: 3

Related Questions