PHP检查SSN的长度

标签 php regex

我们正在尝试为我们的招生办公室设置在线申请,我们需要对社会安全号码进行错误检查以确保它们输入了有效值。 xxx-xx-xxxx 或仅 9 位数字。我已经尝试了几次迭代,这就是我现在所做的:

$ssn = $form_values['submitted_tree']['biographical_information']['social_security_number'];

if (strlen($ssn) > 0 && preg_match('/^([0-9]){3}(([ ]|[-])?([0-9]){2})(([ ]|[-])?([0-9]){4})?$/', $ssn) == 0) { 
    form_set_error('submitted][biographical_information][social_security_number', t('You must enter a valid Social Security Number: ###-##-####')); 
}

最佳答案

为什么不简单地从字符串中删除任何 - 然后验证它是 9 位数字?

$ssn = ...;
$ssn_validate = str_replace('-', '', $ssn);
$pattern = '/^[0-9]{9}$/';
if(preg_match($pattern, $ssn_validate)) {
    // it matched
}

关于PHP检查SSN的长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22257139/

相关文章:

php - 让所有用户使用 OOP 的正确方法

Javascript 正则表达式匹配某些字符串,但在其他看似相同的字符串上失败

javascript - JS : Replace a number with trailing zeros to scientific notation

HTML数据提取

php - 如何在 codeigniter 中使用 ajax 将数据插入 mysql 数据库?

php - 禁用 Woocommerce 产品类别存档页面上的“添加到购物车”按钮

python - 我不明白为什么这个 URL 匹配正则表达式不起作用

javascript - AngularJS 标签中的单引号

php - reCaptcha:错误代码 "invalid-keys"

PHP fatal error : Class 'InvalidArgumentException' not found in <file> on line X?