简体   繁体   English

正则表达式,用于包含至少8个字符和至少1个非字母数字字符的密码

[英]Regular Expression for a password with at least 8 characters and at least 1 non-alphanumeric character(s)

I am trying to make a check in PHP if a user changes their password their new password must be 8 or more characters and with at least 1 non-alphanumeric password. 我试图在PHP中进行检查,如果用户更改了他们的密码,他们的新密码必须是8个或更多字符,并且至少有1个非字母数字密码。 How should I check this and what would the regex be? 我该怎么检查这个以及正则表达式是什么?

Checking the length is the easy part strlen >= 8 . 检查长度是容易的部分strlen >= 8 My problem is regular expressions. 我的问题是正则表达式。 I really have no clue about regular expressions even after years of studying computer science. 即使经过多年的计算机科学研究,我对正则表达式也一无所知。

Thanks 谢谢

Try something like this to check if they used non-alphanumeric characters: 尝试这样的方法来检查它们是否使用了非字母数字字符:

if( !preg_match( '/[^A-Za-z0-9]+/', $password) || strlen( $password) < 8)
{
    echo "Invalid password!";
}

The if statement will evaluate to true if the $password does not contain at least one of the characters not in the list (alphanumeric characters). if $password不包含列表中不包含的至少一个字符(字母数字字符), if语句将评估为true

This should work (untested) 这应该工作(未经测试)

if (preg_match('/^(?=.*[\W])(?=[a-z0-9])[\w\W]{8,}$/i', '123abc!$'))
{
    //error
}

It makes sure the password is 8 characters long and has at least one special character 它确保密码长度为8个字符,并且至少包含一个特殊字符

If you're checking the string length with strlen/mb_strlen, you can simply write a regular expression to match any non-alphanumeric character. 如果使用strlen / mb_strlen检查字符串长度,则只需编写正则表达式即可匹配任何非字母数字字符。 If it matches one (or more), you're good. 如果它匹配一个(或更多),你就是好的。 For example: 例如:

$password = 'asdf123!';

if(mb_strlen($password) >= 8 and preg_match('/[^0-9A-Za-z]/', $password))
{
    // password is valid
}

To my knowledge, you can't achieve this because it's a composite condition scenario. 据我所知,你无法实现这一点,因为它是一个复合条件场景。

What you'd need to do is do it in a three step fashion: 你需要做的是以三步的方式做到这一点:

$has8characters = (mb_strlen($_REQUEST['password']) >= 8);
$hasAlphaNum = preg_match('b[a-z0-9]+bi', $_REQUEST['password']);
$hasNonAlphaNum = preg_match('b[\!\@#$%\?&\*\(\)_\-\+=]+bi', $_REQUEST['password']);

This wasn't tested, but you are pretty close of what you want to achieve with this... 这没有经过测试,但你已经非常接近你希望通过这个...

Good luck 祝好运

Try this. 试试这个。

~^(.*[\W]+.*){8,}$~
  • .* looks for any character 0 or more times 。*查找任何字符0次或更多次
  • [\\W]+ matches at least one non-word character [\\ W] +匹配至少一个非单词字符
  • {8,} matches the bracketed value only if the length is 8 or more characters 仅当长度为8个或更多字符时,{8,}才匹配括号内的值
  • ^ $ match the start and end of the string ^ $匹配字符串的开头和结尾

This solves it. 这解决了它。 Have a try! 试试!

if(!preg_match('/^(?=.*\d)(?=.*[A-Za-z])[0-9A-Za-z!@#$%]{8,}$/', $pass)) {
  echo "Password does not meet the requirements! It must be alphanumeric and atleast 8 characters long";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM