Generate regular expression dynamically that accepts Mobile ph. with country code and number length

sachin
edited October 2021 in PHP

I want to pass multiple county codes and length of Mobile phone number to create a reguar expression that validates the Mobile number on behalf of passed country code and length

Answers

  • $regex = "";
    
    $consecutive_array = array();
    
    $only_numbers = 1;
    $add_wl_cc = array('1','41','91');
    $callerid_len = array('9','10','12','13','14','15','18');
    $callerid_len = array_map(function($arr){return (int)$arr;}, $callerid_len);
    sort($callerid_len);
    
    if($add_wl_cc){
        $regex = "^(".implode('|', $add_wl_cc).")".$regex;
    }
    
    if($callerid_len){
        $temp = array();
        array_push($temp, $callerid_len[0]);
        for ($i=1; $i < sizeof($callerid_len); $i++) { 
            if($callerid_len[$i-1]+1 == $callerid_len[$i]){
                $temp[] = $callerid_len[$i];
            }else{
                $consecutive_array[] = $temp;
                $temp = array();
                $temp[] = $callerid_len[$i];
            }
    
            if($i == sizeof($callerid_len) - 1){
                $consecutive_array[] = $temp;
                $temp = array();
            }
        }
    
        $consecutive_array = array_map(function($arr){
            $len = sizeof($arr);
            if($len == 1){
                return "\\d{".$arr[0]."}";
            }else{
                return "\\d{".$arr[0].",".end($arr)."}";
            }
        }, $consecutive_array);
        $regex = $regex."(".implode('|', $consecutive_array).")";
    }elseif($only_numbers){
        $regex = "(\d{8,15})";
    }
    
    $regex = $regex."$";
    
    echo "<pre>";
    print_r($consecutive_array);
    echo "</pre>";
    
    
    echo $regex;
    echo '<br>';
    

    Result will be
    ^(1|41|91)(\d{9,10}|\d{12,15}|\d{18})$
    which will accepts numbers start with 1,41,91 having lenghth 9,10,12,13,14,15,18

Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!