user1463637
user1463637

Reputation:

Regular expression needed for specific string in PHP

I need a regular expression to validate a string with the following conditions

  1. String might contain any of digits space + - () / .
    If string contain anything else then it should be invalid
  2. If there is any + in the string then it should be at the beginning and there should at most one + , otherwise it would be invalid, if there are more than one + then it is invalid
  3. String should be 7 to 20 character long
  4. It is not compulsory to have all these digits space + - () / .
    But it is compulsory to contain at least 7 digit

Upvotes: 1

Views: 179

Answers (4)

Shiplu Mokaddim
Shiplu Mokaddim

Reputation: 57660

I think you are validating phone numbers with E.164 format. Phone number can contain many other format. It can contain . too. Multiple spaces in a number is not uncommon. So its better to format all the numbers to a common format and store that format in db. If that common format is wrong you can throw error.

I validate those phone numbers like this.

function validate_phone($phone){
    // replace anything non-digit and add + at beginning
    $e164 = "+". preg_replace('/\D+/', '', $phone);
    // check validity by length;
    return (strlen($e164)>6 && strlen($e164)<21);
}

Here I store $e164 in Db if its valid.

Even after that you can not validate a phone number. A valid phone number format does not mean its a valid number. For this an sms or call is generated against the number and activation code is sent. Once the user inputs the code phone number is fully validated.

Upvotes: 2

Ry-
Ry-

Reputation: 225005

A little more concise:

^\+?(?=(.*\d){7})[()/\d-]{7,19}$

'Course, why would you even use regular expressions?

function is_valid($string) {
    $digits = 0;
    $length = strlen($string);

    if($length < 7 || $length > 20) {
        return false;
    }

    for($i = 0; $i < $length; $i++) {
        if(ctype_digit($string[$i])) {
            $digits++;
        } elseif(strpos('+-() ', $string[$i]) === false && ($string[$i] !== '+' || $i !== 0)) {
            return false;
        }
    }

    return $digits >= 7;
}

Upvotes: 0

Martin Baulig
Martin Baulig

Reputation: 3010

Let's try ...

preg_match('/^(?=(?:.*\d){7})[+\d\s()\/\-\.][\d\s()\/\-\.]{6,19}$/', $text);

Breaking this down:

  • We start with a positive look-ahead that requires a digit at least 7 times.
  • Then we match all the valid characters, including the plus.
  • Followed by matching all the valid characters without plus between 6 and 20 times.

Upvotes: 1

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324710

You can do this in one regex:

/^(?=(?:.*\d){7})[0-9 ()\/+-][0-9 ()\/-]{6,19}$/

However I would personally do something like:

/^[0-9 ()\/+-][0-9 ()\/-]{6,19}$/

And then strip any non-digit and see if the remaining string is 7 or longer.

Upvotes: 1

Related Questions