Validating US phone number with php/regex

后端 未结 5 557
误落风尘
误落风尘 2020-11-30 08:11

EDIT: I\'ve mixed and modified two of the answers given below to form the full function which now does what I had wanted and then some... So I figured I

5条回答
  •  心在旅途
    2020-11-30 08:40

    Well, you could modify the regex, but it won't be very nice -- should you allow "extn"? How about "extentn"? How about "and then you have to dial"?

    I think the "right" way to do this is to add a separate, numerical, extension form box.

    But if you really want the regex, I think I've fixed it up. Hint: you don't need [x] for a single character, x will do.

    /^\(?(\d{0,3})\)?(\.|\/)|\s|\-)?(\d{3})(\.|\/)|\s|\-)?(\d{4})\s?(x|ext)?(\d*)$/
    

    You allowed a dot, a slash, a dash, and a whitespace character. You should allow only one of these options. You'll need to update the references to $matches; the useful groups are now 0, 2, and 4.

    P.S. This is untested, since I don't have a reference implentation of PHP running. Apologies for mistakes, please let me know if you find any and I'll try to fix them.

    Edit

    This is summed up much better than I can here.

提交回复
热议问题