【问题标题】:PHP preg_match regex not workingPHP preg_match 正则表达式不起作用
【发布时间】:2013-06-19 10:57:54
【问题描述】:

我正在尝试验证美国电话号码的字段,如果输入到该字段中的信息无效,则返回错误。它目前不接受任何输入为有效的信息,即使正则表达式似乎有效:

add_action('register_form','myplugin_register_form2');
function myplugin_register_form2 (){
    $phone_number = ( isset( $_POST['phone_number'] ) ) ? $_POST['phone_number']: '';
    ?>
    <p id="phone_number">
        <label for="phone_number"><?php _e('Phone Number <font size="1">(XXX XXX XXXX)</font>','mydomain') ?><br />
            <input type="text" name="phone_number" id="phone_number" class="input" size="25" style="text-align:right" maxlength="14" />
    </p>
    <?php
}

//2. Phone_number Requirement
add_filter('registration_errors', 'myplugin_registration_errors2', 10, 3);
function myplugin_registration_errors2 ($errors, $sanitized_user_login, $user_email) {
$pattern = '/^(?:1(?:[. -])?)?(?:\((?=\d{3}\)))?([2-9]\d{2})(?:(?<=\(\d{3})\))? ?(?:(?<=\d{3})[.-])?([2-9]\d{2})[. -]?(\d{4})(?: (?i:ext)\.? ?(\d{1,5}))?$/';
if (!preg_match($pattern, $phone_number, $matches))
{
        $errors->add( 'phone_number_error', __('<strong>ERROR</strong>: You must include a valid phone number.','mydomain') );

    return $errors;
} 

    if ( empty( $_POST['phone_number'] ) )
        $errors->add( 'phone_number_error', __('<strong>ERROR</strong>: You must include a valid phone number.','mydomain') );

    return $errors;
}

【问题讨论】:

  • 尝试在输入字段上使用 trim 或尝试其他正则表达式。
  • 感谢 Aragon0,但是当使用上面的正则表达式并调整最后的代码位以匹配我正在寻找的函数时 `foreach($aNumbers as $sNumber) { if (!preg_match($sPattern, $ phone_number, $aMatches)) { $errors->add( 'phone_number_error', __('ERROR: 你必须包含一个有效的电话号码。','mydomain') );返回$错误; } }' 这是行不通的。它一直告诉我号码无效。
  • functions-online.com/preg_match.html 试用您的正则表达式。
  • ERROR: missing ) at offset 1639 - 这是使用您引用的帖子中给出的正则表达式。我没有改变任何东西。

标签: php regex validation preg-match field


【解决方案1】:

好的,我找到了一个没有错误的方法:

/^(?:(?:(?:1[.\/\s-]?)(?!\())?(?:\((?=\d{3}\)))?((?(?!(37|96))[2-9][0-8][0-9](?<!(11)))?[2-9])(?:\((?<=\(\d{3}))?)?[.\/\s-]?([0-9]{2}(?<!(11)))[.\/\s-]?([0-9]{4}(?<!(555(01([0-9][0-9])|1212))))(?:[\s]*(?:(?:x|ext|extn|ex)[.:]*|extension[:]?)?[\s]*(\d+))?$/

但你必须先去掉所有非数字:

$input_number=preg_replace("[^0-9]","",$input_number);

您还可以根据需要格式化您的号码:

preg_match($pattern,$input_number);
$number=$result[1] . "-" . $result[4] . "-" . $result[6];

另一种方法是使用 jQuery 设置输入掩码,如我上面提到的线程中所述。那么用户只能输入一个有效的电话号码。

我没有找到匹配多种格式的好正则表达式。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-05
    • 2014-06-28
    • 1970-01-01
    • 2015-09-21
    • 2020-03-31
    相关资源
    最近更新 更多