Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
418 views
in Technique[技术] by (71.8m points)

php - Regular expression to match 7-12 digits; may contain space or hyphen

I have been trying to solve a PHP regular expression problem for awhile now but I just can't quite get it done. I need write a regex that will match between 7 and 12 digits (0..9) and there may optionally be either a single hyphen or a single space between adjacent digits. This is what I have so far...

$match1 = preg_match('/^d[0-9-s]{5,10}d$/', $number);
$match2 = preg_match('/(-s|s-|--|ss)/', $number);

As you can see I have to use two different checks and it still isn't enough for me as I can input this string: "1-2-3-4-5" and it will still pass because there are a total of 9 characters but it should fail because there are only 5 digits.

Any help on the matter would be great, thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

How about:

/^(d[-s]?){6,11}d$/

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...