tags:

views:

39

answers:

4

I have input, I want to check it.

It should accept only numbers, and must be 16, no more and no less.

How I can do that using php and regex?

+3  A: 

Regex would be ^\d{16}$

preg_match("/^\\d{16}$/", $str);
Amarghosh
IMO, it's better to use single quotes on matching string, since it prevents unexpected results, like forgetting to escape backslash or other special characters (namely $). Not that you made any of these mistakes, quite contrary. I had several nasty bugs that were due to using double quotes, and learned my lesson.
mr.b
@mr.b Appreciate that. I hardly know PHP; learned it for answering some regex/flash related questions on SO. I assume `$` variables are not expanded in single quoted strings - lemme google for more details.
Amarghosh
In this case it's not expanded since it's not followed by a letter(s), however, if you were to put $abc (for some reason), that *would* break your party. And no, single quoted strings do not expand variables.
mr.b
@mr.b Thanks :)
Amarghosh
+2  A: 
^\d{16}$

Explication:

  • ^ for the beginning of the line (so nothing before that)
  • \d meaning a number (decimbal)
  • {16} to mean "exactly 16"
  • $ for the ending of the line (so nothing after that)
Konerak
A: 

I think you need it for the credit card validator

^(\d{4}[- ]){3}\d{4}|\d{16}$

this will match :

1234-1234-1234-1234 | 1234 1234 1234 1234 | 1234123412341234

Please note that this is copied from regexlib

VoodooChild
If you are going to parse "real world formats", be lenient. Be friendly to your users. Remove everything that is not a number, parse the 16 numbers, then apply the format. This way even typo's like "12341234 1234.1234" get parsed correctly.
Konerak
A: 

Would it not be better to make sure its 16 characters and numbers only with is_numeric() and strlen().

red-X