0

I know there are lots of same type of questions posted on stackoverflow but I have something in custom and dont know how to solve this problem.

If any number is prefixed with ‘+’ or 0 (sequence of zero like 00) or ‘91-‘, then it should be removed automatically before group creation. prefixed needs to be removed -

  1. 0 or sequence of 0 (00, 000, 0000 etc)
  2. +
  3. 91-
  4. +91-

Valid mobile numbers entered by users should be as below:

  1. If mobile number is 10 digit, it should start with 9,8,7 or 6
  2. If mobile number is 12 digit, first 2 digits should be 91 and 3rd digit should be 9,8,7 or 6 All other numbers should be considered invalid for domestic group creation.

What will be the php code for above as will be?

phone no ex-

  1. +918877665544 or 0918877665544 or 0000918877665544 will give 918877665544 (length 12)
  2. +91-8877665544 or 91-8877665544 or 00008877665544 will give 8877665544 (length 10)
  3. +91-88776655440 (length 11) or 91-88-77665544 (- in between) will give gets skip or should giv blank

only digits are allowed after removing the allowed prefixes.

if any other it should skip (should give blank).

Note:- for all the cases it should have only one regex as this regex will be inserted from config settings.

Vikas Chauhan
  • 1,276
  • 15
  • 23

1 Answers1

1

One option could be using optional parts at the start of the pattern:

^\+?0*(?:91-)?\K(?:91)?[6-9][0-9]{9}$
  • ^ Start of string
  • \+?0*(?:91-)? Optionally match +, 0+ times a 0 or 91-
  • \K Forget what was matched
  • (?:91)? Optionally match 91
  • [6-9][0-9]{9} Match a digit 6-9 and 9 digits 0-9
  • $ End of string

Regex demo | Php demo

If you don't want to use anchors ^ and $ you could use lookaround assertions to make sure what is directly on the left and right is not a non whitespace char:

(?<!\S)\+?0*(?:91-)?\K(?:91)?[6-9][0-9]{9}(?!\S)

Regex demo | Php demo

The fourth bird
  • 154,723
  • 16
  • 55
  • 70