0

我专门针对数字,所以如果我在前端使用使用 javascript 的电话掩码,将用户输入过滤到 (000)000-000,基本上 [2-9] 和 [0-9] 作为掩码(jquery.maskedinput -1.3.js ) 和移动过滤器...

jQuery(function ($e) {
var isMobile = navigator.userAgent.match(/(iPhone|iPod|iPad|Android|BlackBerry)/);
$e('#refer').val(window.location.href);

if (!(isMobile)) {      
    $e('#phone').mask('(299)299-9999');
    $e('#field_phone_number').mask('299-299-9999');
}
}); 

对于服务器端,我在 PHP 中有一个正则表达式(还没有什么特别的)

function phonenumber($value)
{
    return preg_match("/\(?\b[(. ]?[0-9]{3}\)?[). ]?[0-9]{3}[-. ]?[0-9]{4}\b/i", $value);
} 

如何创建一个针对所有数值的正则表达式或 php 脚本,而不为每个字符创建一个很长的正则表达式?我只想知道如果有人输入 (222)222-2222,他们在返回时会得到错误的结果。

4

2 回答 2

2
function phonenumber($value)
{
    $prefix = '\d{3}'; // You might want to specify '2\d\d' (200 to 299)
    $regex = '#^(\('.$prefix.'\)|'.$prefix.')[\s\.-]?\d{3}[\.-]?\d{4}$#';
    if (preg_match($regex, $value))
    {
        // Number is in a suitable format

        // Now extract digits -- remove this section to not test repeated pattern
        $digits = preg_replace('#[^\d]+#', '', $value);

        // All numbers equal are rejected
        if (preg_match('#^(\d)\1{9}$#', $digits))
            return false;
        // end of pattern check

        // Otherwise it is accepted
        return true;
    }
    return false; // Not in a recognized format
}

这将接受 (299)423-1234 和 277-111-2222,以及 (400)1234567 或 4001234567。它将拒绝 (400-1234567 和 400-12-34-56-7。它还将拒绝 (222) 222-2222 因为重复的 2。

于 2012-11-02T23:03:24.797 回答
1

您可以使用反向引用\1来检测重复出现的模式。在您的情况下,您可以简单地混合 a.*以忽略中间填充物,例如(-

  /(\d)(.*\1){7}/

将查找一个数字,并至少重复 7 次相同的数字,忽略用作填充符的任何其他字符。但是,这并不能确保它们是连续的,因此(222)222-8222也会匹配。

于 2012-11-02T22:51:19.107 回答