You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP中preg_match无法匹配连字符(-)的问题求助

PHP中preg_match无法匹配连字符(-)的问题求助

我正在开发一个强密码校验的PHP功能,需求是:密码长度至少6位,必须包含大写字母、小写字母、数字,以及指定的特殊字符(!@#$%^&*()-+),最终计算出需要补充多少字符才能让密码符合强密码标准。

目前其他校验逻辑都正常工作,但唯独发现preg_match无法匹配连字符-,除了这个符号之外,其他指定的特殊字符都能被正确识别。我是不是在正则表达式里犯了什么错误?

我的代码如下:

<?php

/*
* Complete the 'minimumNumber' function below.
*
* The function is expected to return an INTEGER.
* The function accepts following parameters:
*  1. INTEGER n
*  2. STRING password
*/

function minimumNumber($n, $password) {

// Return the minimum number of characters to make the password strong
$count = 0;

// Return the minimum number of characters to make the password strong
if (!preg_match( '~[A-Z]~', $password)) {
$count += 1;
}

if (!preg_match( '~[a-z]~', $password)) {
$count += 1;
}

if (!preg_match( '~[0-9]~', $password)) {
$count += 1;
}

if (!preg_match( '~[!@#$%^&*()-+]~', $password)) {
echo 'hit';
$count += 1;
}

if ($n + $count < 6) {
$count += 6 - ($n + $count);
}

return $count;
}

$fptr = fopen(getenv("OUTPUT_PATH"), "w");

$n = intval(trim(fgets(STDIN)));
$password = rtrim(fgets(STDIN), "\r\n");

$answer = minimumNumber($n, $password);

fwrite($fptr, $answer . "\n");

fclose($fptr);

问题原因

问题出在你的正则表达式字符集里:~[!@#$%^&*()-+]~。在正则的[]字符集中,连字符-是有特殊作用的——它用来定义字符范围(比如0-9表示0到9的数字,A-Z表示大写字母范围)。你当前的写法中,()-+会被解析成从(到+的ASCII字符范围,而不是把-当作一个独立的特殊字符来匹配,所以自然识别不了单独的-符号。

解决方案

你可以通过两种方式修复这个问题:

  • 把连字符放在字符集的开头或末尾:这样正则就不会把它当作范围符号,而是普通字符。比如:
    if (!preg_match( '~[-!@#$%^&*()+]~', $password)) {
    
    或者:
    if (!preg_match( '~[!@#$%^&*()+-\]~', $password)) {
    }
    
  • 给连字符添加转义符:用\-来表示普通的连字符,这样正则就会正确识别它:
    if (!preg_match( '~[!@#$%^&*()\-+]~', $password)) {
    }
    

修改之后,再测试包含-的密码,就能正常触发这个特殊字符的校验逻辑了。

备注:内容来源于stack exchange,提问作者Ganeshkumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.21 15:48:01