这些符号在preg_match中意味着什么?

mar*_*oko 6 php preg-match

我在离线借用的代码片段中有这个表达式.它强制新用户拥有一个密码,不仅需要上+下+数字,而且必须按顺序排列!如果我输入较低+上+数字,则失败!

if (preg_match("/^.*(?=.{4,})(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).*$/", $pw_clean, $matches)) {
Run Code Online (Sandbox Code Playgroud)

我在网上搜索但找不到能告诉我一些字符含义的资源.我可以看到模式是preg_match("/ some expression /",yourstring,你的匹配).

这些是什么意思:

1.  ^          -  ???
2.  .*         -  ???
3.  (?=.{4,})  -  requires 4 characters minimum
4.  (?.*[0-9]) -  requires it to have numbers
5.  (?=.*[a-z])-  requires it to have lowercase
6.  (?=.*[A-Z])-  requires it to have uppercase
7.  .*$        -  ???
Run Code Online (Sandbox Code Playgroud)

cco*_*rup 15

以下是直接答案.我保持简短,因为如果不了解正则表达式就没有意义.这种理解最好在regular-expressions.info上获得.我建议你也试试那里列出的正则表达式助手工具,它们允许你进行实验 - 在编辑模式时看到实时捕捉/匹配,非常有帮助.


1:插入符号^是一个锚点,它表示"干草堆/字符串/行的开头".

  • 如果插入符号是字符类中的第一个符号[],则它具有不同的含义:它否定了类.(因此在[^ab]插入符号中使该类匹配任何不是 ab的内容)

2:圆点.和星号*有两个不同的用途:

  • 该点匹配除换行符之外的任何单个字符\n.
  • 星号表示"允许零或许多先前类型".

当这两者结合在一起时,.*它基本上是"零或更多的东西,直到换行或其他规则生效".

7:美元$也是像插入符号一样的锚点,具有相反的功能:"大海捞针".


编辑:

( )围绕着某些东西的简单括号使它成为一个群体.在这里你有(?=)一个断言,特别是一个积极的前瞻断言.它所做的就是检查大海捞针当前光标位置内部实际存在的内部.还在我这儿?
示例: 仅在后跟时foo(?=bar)匹配.从不匹配,只返回.foobarbarfoo

考虑到这一点,让我们剖析你的正则表达式:

/^.*(?=.{4,})(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).*$/

Reads as:
        ^.* From Start, capture 0-many of any character
  (?=.{4,}) if there are at least 4 of anything following this
(?=.*[0-9]) if there is: 0-many of any, ending with an integer following
(?=.*[a-z]) if there is: 0-many of any, ending with a lowercase letter following
(?=.*[A-Z]) if there is: 0-many of any, ending with an uppercase letter following
        .*$ 0-many of anything preceding the End
Run Code Online (Sandbox Code Playgroud)

你说密码字符的顺序很重要 - 它不在我的测试中.请参阅下面的测试脚本 希望这清理了一两件事.如果您正在寻找另一个更宽容的正则表达式,请参阅正则表达式密码验证

<pre>
<?php
// Only the last 3 fail, as they should. You claim the first does not work?
$subjects = array("aaB1", "Baa1", "1Baa", "1aaB", "aa1B", "aa11", "aaBB", "aB1");

foreach($subjects as $s)
{
    $res = preg_match("/^.*(?=.{4,})(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).*$/", $s, $matches);
    echo "result: ";
    print_r($res);

    echo "<br>";
    print_r($matches);
    echo "<hr>";
}
Run Code Online (Sandbox Code Playgroud)

用于检查和测试正则表达式的优秀在线工具:https: //regex101.com/