Treps
Treps

Reputation: 800

PHP: preg_match -> Numbers and ONE hyphen

I want a regex that accepts ONLY letters and ONE hyphen. The value has to start with 5- (five and one hyphen) and just 5-15 numbers after.

I'm currently using: preg_match('/^[5]-{1}[\0-9]{5,15}$/', $_POST['value'])

A valid value is: 5-123456789

My regex accepts two hyphens like 5--123456789. It has to start with 5, ONE hyphen and 5-15 numbers. How should I do that?

Thanks in advance!

Upvotes: 0

Views: 1819

Answers (2)

Jon
Jon

Reputation: 437854

The problem is that you specified the digits wrong: [\0-9] matches any character whose index is between zero and that of 9 -- in ASCII terms, characters with indexes 0 to 57. The hyphen has an index of 45, so it's allowed. This happens because \0 is interpreted as an octal escape sequence.

You should use [0-9]{5,15} or \d{5,15} instead. You can also simplify the regex somewhat; /^5-\d{5,15}$/ is correct and shorter.

Upvotes: 4

b4rt3kk
b4rt3kk

Reputation: 1569

You used \ before 0, that means that it's not a range 0-9 but 0 and -9, so this is your second hyphen here (but it's optional, cause in brackets []). Just remove this \ from brackets. Leave it like this:

preg_match('/^[5]-{1}[0-9]{5,15}$/', $_POST['value'])

Even this notation is correct:

preg_match('/^5-[0-9]{5,15}$/', $_POST['value'])

Upvotes: 1

Related Questions