bernzkie
bernzkie

Reputation: 1269

PHP - preg_match for only numbers and single dash

Let's say I only allow this kind of format 2015-2016 which contains number and only one dash. How can I do this with preg_match? I tried the following, but with no luck.

$a = '2015-2016';
if(!preg_match('/[^0-9\-]/i',$a)) {
    then return not valid data`
} 

Upvotes: 1

Views: 9724

Answers (2)

Crunch Much
Crunch Much

Reputation: 1527

Hope this will help

preg_match('/^\d{4}-\d{4}$/', $string);

^ Start of the string

\d{4} match a digit [0-9] Exactly 4 times

- matches the character - literally

\d{4} match a digit [0-9] Exactly 4 times

$ End of the string

Upvotes: 5

Chris G
Chris G

Reputation: 780

$a = '2015-2016';
if(!preg_match('/^[0-9 \-]+$/',$a)) {
 then return not valid data } 

Try that.

Upvotes: 2

Related Questions