如何使用preg_match进行验证用户名?

时间:2018-02-05 01:11:57

标签: php regex

我想创建一个preg_match函数来验证我的用户名,下面的代码不能正常运行,特别是Must contain at least 4 letter lowercase规则和number not more than 4 character and place behind letter

if (preg_match('/^[a-z0-9]{4,12}/', $_POST['username']))

以下是我想要使用的用户名规则:

  • 仅包含字母和数字,但不需要数字
  • 必须至少包含4个小写字母
  • 数字不超过4个字符并且放在字母后面
  • 必须是4-12个字符

感谢您提供任何帮助。

2 个答案:

答案 0 :(得分:1)

您符合这些标准,也许这是一个选项:

^[a-z](?=(?:[a-z]*\d){0,4}(?![a-z]*\d))(?=[a-z\d]{3,11}$)[a-z\d]+$

这将匹配

  • 从字符串^
  • 的开头
  • 匹配小写字符[a-z]
  • 一个积极的前瞻(?=,断言以下是
    • 非捕获组(?:
    • 匹配小写字符零次或多次,后跟数字[a-z]*\d
    • 关闭非捕获组并重复0到4次){0,4}
    • 否定前瞻(?!断言后面的内容不是
    • 小写字符零次或多次,后跟数字[a-z\d]*
    • 关闭否定前瞻)
  • 关闭正面预测)
  • 肯定前瞻(?=,断言以下是
    • 将小写字母或数字从3到11次匹配,直到字符串结尾(?=[a-z\d]{3,11}$)
  • 关闭正面预测)
  • 匹配小写字符或数字,直到字符串[a-z\d]+$
  • 的结尾

Out php example

答案 1 :(得分:0)

正则表达式^[a-z]{4,8}[0-9]{0,4}$|^[a-z]{4,12}$

详细说明:

  • ^在行的开头断言位置
  • $断言位于行尾的位置
  • []匹配列表中的单个字符
  • {n,m} nm次之间的匹配
  • |

PHP代码

$strings=['testtesttest', 'testtesttestr', 'test12345', 'testtest1234', 'testte123432'];

foreach($strings as $string){
    $match = preg_match('~^[a-z]{4,8}[0-9]{0,4}$|^[a-z]{4,12}$~', $string);
    echo ($string . ' => len: (' . strlen($string) . ') ' .($match ? 'true' : 'false')."\n");
}

输出:

testtesttest => len: (12) true
testtesttestr => len: (13) false
test12345 => len: (9) false
testtest1234 => len: (12) true
testte123432 => len: (12) false

Code demo

相关问题