Phone number validation in PHP

后端 未结 3 879
渐次进展
渐次进展 2021-01-23 07:21

I need to validate phone number in PHP. I have made following regex, but I also need to it to accept numbers starting with plus char, how can I do that?

^[0-9]$         


        
3条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-23 08:13

    The regex you provided in your question (^[0-9]$) will only match a one digit phone number.

    At the very least you probably need to add the + modifier to allow one or more digits:

    ^[0-9]+$
    

    To add an optional + at the beginning, you'll need to escape it since + is a special character in regular expressions:

    ^\+?[0-9]+$
    

    And finally, \d is shorthand for [0-9] so you could shorten the expression to

    ^\+?\d+$
    

提交回复
热议问题