2

I've been searching for hours to find a regex that does this for me, all the ones I've found either require dashes or limit something else that I don't need.

Like this one: ^(?([0-9]{3}))?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$

Basically I want to allow these types of input for phone number, these are all valid:

+000 111111111

+00011111111111

0022 111111111111

0022111111111

+333-4444-5555-6666

000-7878787-0000-4587

Note that the number of digits is not limited, I only want the validation to filter out empty inputs and the alphabet. Also filter out all other characters except a maximum of 4 dashes, max. 4 spaces and an optional single plus sign.

Is this possible through preg_match or not?

Any help is appreciated, thanks!

Claudio Delgado
  • 2,239
  • 7
  • 20
  • 27
  • Related: http://stackoverflow.com/questions/123559/a-comprehensive-regex-for-phone-number-validation and http://stackoverflow.com/questions/2113908/what-regular-expression-will-match-valid-international-phone-numbers – Phill Pafford Jul 20 '11 at 14:35
  • $numSpaces = preg_match_all('/[ ]/', $phone, $matches); $numDashes = preg_match_all('/[-]/', $phone, $matches); $numPlus = preg_match_all('/[+]/', $phone, $matches); if (!empty ($phone) && (is_numeric($phone))) { if (($numSpaces <= 4) && ($numDashes <= 4) && ($numPlus <= 1)) { $validphone = true; } } else { $validphone = false; } – Claudio Delgado Jul 20 '11 at 15:23

2 Answers2

2

Sure its possible. But to my opinion dangerous to use stuff that is not understood. I would do something like this

^(?!(?:\d*-){5,})(?!(?:\d* ){5,})\+?[\d- ]+$

See it here on Regexr

The last part \+?[\d- ]+ allows an optional + followed by at least one digit, dash or space

The negative lookaheads ensure that there are not more than 4 dash or spaces.

Limitations:
- The dash or space can be in one row
- it accepts also - as valid

Try it yourself on the Regexr link, you can just add examples what you want.

stema
  • 90,351
  • 20
  • 107
  • 135
  • Before seeing your answer, using James's advice, I did this: – Claudio Delgado Jul 20 '11 at 15:20
  • $numSpaces = preg_match_all('/[ ]/', $phone, $matches); $numDashes = preg_match_all('/[-]/', $phone, $matches); $numPlus = preg_match_all('/[+]/', $phone, $matches); if (!empty ($phone) && (is_numeric($phone))) { if (($numSpaces <= 4) && ($numDashes <= 4) && ($numPlus <= 1)) { $validphone = true; } } else { $validphone = false; } – Claudio Delgado Jul 20 '11 at 15:20
1

Strip wanted characters out (" ", "-"), count the amount then chuck an if statement if count <= 4 (for the "+" character it would be == 1). So in total it would be

if (countSpace <= 4 && countDash <= 4 && countPlus == 1) { ... }

As for being empty, just use the standard form validation for checking if the input has been filled or not.

Ojame
  • 169
  • 1
  • 1
  • 9