PHP 中的简单正则表达式模式


Simple regex pattern in PHP

我需要匹配字符串的前几个字符。在以下情况下,匹配为真:

  1. 第一个字符是字母(不区分大小写)
  2. 第二个字符是数字或字母
  3. 如果第二个字符是数字,则返回匹配项 true
  4. 如果第二个字符是字母,则第三个字符必须是数字
  5. 该模式将忽略字符串中的所有其他后续字符

例子:

AB1ghRjh  //true
c1        //true
G44       //true
Tt7688    //true
kGF98d    //false
4FG3      //false
4 5a      //false
RRFDE     //false

如果有人能提供一个例子,将不胜感激。

多谢!

正则表达式将是

^[a-zA-Z]('d|[a-zA-Z]'d).*
/^(?:[a-z]{2}|[a-z])'d.*$/im

解释:

^   # Start of string
    (?: # Start non-capturing group
        [a-z]{2}    # Two letter
        |   # OR
        [a-z]   # One letter
    )   # End of non-capturing group
    'd  # At least a digit here
    .*  # Escape all other characters
$   # End of string

i标志表示不区分大小写,m标志表示使^$每行进行匹配(如果您的输入没有换行符,则可选)

现场演示

然后使用preg_match函数匹配字符串:

if(preg_match("/^(?:[a-z]{2}|[a-z])'d.*$/i", "AB1ghRjh"))
{
    echo "Matched";
}