使用preg_match验证多种格式

Emm*_*myS 1 php regex preg-match

我有一个电话号码字段,设置为使用preg_match进行验证:

function ValidPhone($phone) {
    return preg_match('/^[0-9]{3}-[0-9]{3}-[0-9]{4}$/', trim($phone));
}
Run Code Online (Sandbox Code Playgroud)

这可确保以xxx-xxx-xxxx格式输入电话号码,并确保其为数字.

我对regexp不太熟悉; 任何人都可以告诉我如何扩展这个以允许多种格式?即xxx xxx xxxx或xxx.xxx.xxxx或(xxx)xxx-xxxx

谢谢.

Sea*_*ght 5

我认为最简单的解决方案就是首先删除所有不是数字的东西:

function ValidatePhone($phone) {
    $phone = preg_replace('/\D+/', '', $phone);
    return strlen($phone) == 10;
}
Run Code Online (Sandbox Code Playgroud)

由于您要验证格式而不是内容,因此应该这样做:

function ValidatePhone($phone) {
    $patterns = array(
        '\d{3}([-\. ])\d{3}\g{-1}\d{4}',
        '\(\d{3}\) \d{3}-\d{4}'
        );

    $phone = trim($phone);

    foreach ($patterns as $pattern) {
        if (preg_match('/^' . $pattern . '$/', $phone))
            return true;
    }

    return false;                                                                                                                   
}
Run Code Online (Sandbox Code Playgroud)