在更新数据库之前,对正则表达式匹配的数据进行格式化


Formatting the data matched by a regular expression before updating a database

我有一个验证,它以特定的方式接受电话号码,并将它们转储到数据库中,但它没有按我想要的方式转换它们。

例如,如果我输入999999999909999999999+919999999999作为电话号码,它将以我输入的方式进入数据库。

无论用户如何输入,我如何以+919999999999样式格式化它?

function validate_phone($input){
    $input = trim($input); //get rid of spaces at either end
    if (preg_match('/^(?:(?:'+|0{0,2})91('s*['-]'s*)?|[0]?)?[789]'d{9}$/',$input) == 1){
        return $input;
    }else{
        return false;
    }
}

根据我的理解,您只需要在+91前缀前加上最后10个数字。

我们首先对正则表达式做一个小修改,在[789]'d{9}周围添加括号来捕获它:

/^(?:(?:'+|0{0,2})91('s*['-]'s*)?|[0]?)?([789]'d{9})$/

然后我们使用preg_match的第三个参数检索捕获,使用变量$m:

preg_match('/^(?:(?:'+|0{0,2})91('s*['-]'s*)?|[0]?)?([789]'d{9})$/', $input, $m)

最后10位将包含在$m[2]中,然后返回+91:

function validate_phone($input){
    $input = trim($input); //get rid of spaces at either end
    if (preg_match('/^(?:(?:'+|0{0,2})91('s*['-]'s*)?|[0]?)?([789]'d{9})$/', $input, $m) == 1){
        return '+91'.$m[2];
    }else{
        return false;
    }
}
测试:

echo "'n".validate_phone('9999999999');
echo "'n".validate_phone('09999999999');
echo "'n".validate_phone('+919999999999');
输出:

+919999999999
+919999999999
+919999999999