spiderling
spiderling

Reputation: 139

match possible letters with numbers

Been searching for an answer without obvious success.

I have a post data check in place using preg_match for posted value of QR12345678. The QR may or may not be submitted. I've used the various preg_match below with no luck.

preg_match('/^[A-Z]{1,3}[0-9]{4,10}$/', $_POST['some_id'])
preg_match('/^[A-Z]{1,3}?[0-9]{4,10}$/', $_POST['some_id'])
preg_match('/([A-Z]{1,3})?[0-9]{4,10}$/', $_POST['some_id'])
preg_match('/^([A-Z]{1,3})?[0-9]{4,10}$/', $_POST['some_id'])
preg_match('/[A-Z]{0,3}[0-9]{4,10}/', $_POST['some_id'])
preg_match('/([A-Z]{1,3})*[0-9]{4,10}$/', $_POST['some_id'])

using preg_match in the following inline condition

 $some_id = isset($_POST['some_id']) 
        && preg_match('/[A-Z]{1,3}*[0-9]{4,10}/', $_POST['some_id'])
    ? $_POST['some_id']
    : 0;

So, $some_id returns 0 no matter what.

Upvotes: 0

Views: 77

Answers (1)

S.B.
S.B.

Reputation: 2969

The error is in the pattern that you're actually using in your code:

> echo preg_match('/[A-Z]{1,3}*[0-9]{4,10}/',"QR12345678");
< PHP Warning:  preg_match(): Compilation failed: nothing to repeat at offset 10 in php shell code on line 1

The part that doesn't work is {1,3}* where you have 2 quantifiers right after each other and the second one (*) doesn't know what to repeat. Either remove the redundant * quantifier or use one of the other suggested patterns:

> echo preg_match('/[A-Z]{1,3}[0-9]{4,10}/',"QR12345678");
< 1
> echo preg_match('/^([A-Z]{1,3})?([0-9]{4,10})$/',"QR12345678");
< 1

Upvotes: 1

Related Questions