本文介绍了使用preg_match识别强密码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我曾想过使用preg_match()来检查是否正确输入了密码。我想要至少1个大写字母,至少1个小写字母,至少一个数字,以及至少一个特殊字符。这是我正在使用的:

I had thought to use preg_match() to check if a password is correctly entered. I want at least 1 uppercase letter, at least 1 lowercase letter, at least one number, and at least one special char. Here's what I am using:

$pattern = "(?=^.{8,}$)((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$";

此正则表达式在HTML的模式字段中正常工作。但我需要确保它也经过旧版浏览器的验证。

This regex is working fine in HTML's "pattern" field. But I need to ensure that it's also verified for older browsers.

我的PHP代码是这样的:

My PHP code is this:

if (!(preg_match($pattern, $loginpassword))) {echo "Password must include one uppercase letter, one lowercase letter, one number, and one special character such as $ or %."; die;}

我认为它工作得很好,除非我使用密码1 @ abcdeF它也失败了匹配。 PHP代码似乎工作,但没有密码匹配,即使它应该适合模式。 HTML5将让它通过,所以我怀疑正则表达式语句是正确的,但有关我在PHP中的设置是有缺陷的。任何人都可以看到我缺少的东西吗?

I thought it was working great except when I use the password 1@abcdeF it also fails to match. The php code seems to work but no password ever matches, even when it SHOULD fit the pattern. HTML5 will let it through so I suspect the regex statement is correct, but something about my setup in PHP is flawed. Can anyone see what I'm missing?

推荐答案

PHP正则表达式也需要正则表达式分隔符,所以使用:

PHP regex needs regex delimiters also, so use:

$pattern = '/(?=^.{8,}$)((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$/';

这篇关于使用preg_match识别强密码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 18:32