检查邮政编码的2个连续数字串

时间:2013-09-19 15:16:09

标签: php regex function math logic

我想查一下字符串,例如。 56401有2个连续数字(5,6)并且反向检查(6,5)并且需要返回false否则为true.I尝试使用preg_match但我不认为它工作正常:

/\d{4}/

有关如何改善这一点的想法吗?

1 个答案:

答案 0 :(得分:0)

我建议不要使用正则表达式:

function has_consecutive_chars($input) {
    $chars = str_split($input);
    for ($i = 1; $i < count($chars); $i++)
    {
        if (abs($chars[$i] - $chars[$i-1]) == 1)
        {
           return true;
        }
    }
    return false;
}

has_consecutive_chars('56401'); // true
has_consecutive_chars('72674'); // true
has_consecutive_chars('53794'); // false

注意,这也适用于非数字(例如'ab'将被计为连续对)。如果您只希望此函数使用数字,我建议您在将字符串传递给此函数之前验证它(正则表达式是一个很好的解决方案)。