0

I am trying to build my regex to validate phone numbers. These are the rules:

  1. Telephones should not contain any characters except numbers and +
  2. Other strings which doesn't start with 06 or +316 or 0316 or 00316 are invalid.

This is what I tried: $telephone = preg_replace('/[^0-9+]/','', $telephone);

removes all characters except + and numbers . Here still I need to check if the + is the first character or not. For example 466116+ or 21323+3122 are invalid.

preg_match('/^(06|+316)/i', $telephone) . I am trying here to add the starting conditions , but it doesn't work . Could you please help me out? I am lost with regex :| Thank you

Attila Naghi
  • 2,535
  • 6
  • 37
  • 59
  • Hi @Wiktor , if it is duplicated how can I add those conditions with the starting strings ? – Attila Naghi Nov 07 '17 at 08:29
  • If you put the ^ inside the bracket it is taken litteraly, you need to put it outside like `/^[0-9+]/` to check if the first character is a number or the + char. It doesnt solve totally your problem but it's a start. – Julien Rousé Nov 07 '17 at 08:29
  • `+` is a special char that must be escaped in a regex – Wiktor Stribiżew Nov 07 '17 at 08:29
  • @WiktorStribiżew I am talking about : `06 or +316 or 0316 or 00316` these parts :) thnx – Attila Naghi Nov 07 '17 at 08:30
  • what's an example of a valid number, not a part of a valid number. how bout an in-valid number. – ArtisticPhoenix Nov 07 '17 at 08:30
  • 1
    You have `'/^(06|\+316)/i'`, just add other alternatives. – Wiktor Stribiżew Nov 07 '17 at 08:31
  • Why is it case insensitive again? `/../i` Because yea those uppercase digits are tricky.... – ArtisticPhoenix Nov 07 '17 at 08:33
  • `+403132136420430+` this will output `403132136420430+` and it should be `+403132136420430` if I am using this `/^[0-9+]/` – Attila Naghi Nov 07 '17 at 08:33
  • 1
    Use the following regex: `^(06\d{a}|\+316\d{b}|0316\d{c}|00316\d{d})` where a,b,c,d should be replaced by the exact number of digits allowed following your different initial formats. – Allan Nov 07 '17 at 08:35
  • Why do you want to preg replace letters for example? I mean just because you remove an "r" from a string doesn't mean the phone number is valid. It could be the user wanted to press 3 or 4 and accidentally pressed "r". Removing the "r" does not mean it's correct. Why not send it back to user and say "you made a mistake, please verify". – Andreas Nov 07 '17 at 08:38

0 Answers0