带注释的正则表达式不起作用

时间:2014-11-06 22:46:10

标签: php regex

以下代码不会产生预期的结果,即使它应该。但是,如果您注释掉使用注释并使用单行版本的模式,它确实有效。你能想到可能出现的问题吗?

define('USER_PASSWORD_MIN_LENGTH', 8);
define('USER_PASSWORD_MAX_LENGTH', 15);

$password = 'mlk45jl64pfw';

//$pattern = '/^(?=[a-zA-Z]*?\d)(?=\d*?[a-zA-Z])[a-zA-Z\d]{8,15}$/x';
///*
$pattern = '/^
             (?=[a-zA-Z]*?\d)                # Checks if the string contains at least one digit
             (?=\d*?[a-zA-Z])                # Checks if the string contains at least one letter either in lower- or upper-case
             [a-zA-Z\d]{                     # Overall the string must consist of only digits and letters, regardless of capitalization for the latter'
             . USER_PASSWORD_MIN_LENGTH . ', # Password minimum length'
             . USER_PASSWORD_MAX_LENGTH . '} # Password maximum length
             $/x';
//*/


if (preg_match($pattern, $password)) {
    echo "<p>Password is valid.</p>\n";
} else {
    echo "<p>Password is not valid.</p>\n";
}

2 个答案:

答案 0 :(得分:0)

在预标记中回显模式会产生以下结果:

/^
             (?=[a-zA-Z]*?\d)                # Checks if the string contains at least one digit
             (?=\d*?[a-zA-Z])                # Checks if the string contains at least one letter either in lower- or upper-case
             [a-zA-Z\d]{                     # Overall the string must consist of only digits and letters, regardless of capitalization for the latter8, # Password minimum length15} # Password maximum length
             $/x

在您以单引号结尾的注释之后,您没有新行,以便在引号内连接,因此下一行显示为注释的一部分。然后你最终会得到一个开口的大括号,这会导致一个糟糕的模式。

答案 1 :(得分:0)

这有用吗?

 '/^
  (?=[a-zA-Z]*?\d)                  # Checks if the string contains at least one digit
  (?=\d*?[a-zA-Z])                  # Checks if the string contains at least one letter either in lower- or upper-case
  [a-zA-Z\d]{                       # Overall the string must consist of only digits and letters, regardless of capitalization for the latter
  ' . USER_PASSWORD_MIN_LENGTH . ', # Password minimum length
  ' . USER_PASSWORD_MAX_LENGTH . '} # Password maximum length
  $/x';