Pet*_*art 14 php regex string special-characters
我目前正在编写一个小脚本来检查每个字符串的内容.
我想知道REGEX将确保字符串有一个字母(上部或下部),一个数字和一个特殊字符?
这是我目前所知的(whcih并不多):
if(preg_match('/^[a-zA-Z0-9]+$/i', $string)):
Run Code Online (Sandbox Code Playgroud)
帮助会很棒!
谢谢!
Ry-*_*Ry- 49
最简单(也可能是最好的)方法是使用以下三种方式进行检查preg_match
:
$containsLetter = preg_match('/[a-zA-Z]/', $string);
$containsDigit = preg_match('/\d/', $string);
$containsSpecial = preg_match('/[^a-zA-Z\d]/', $string);
// $containsAll = $containsLetter && $containsDigit && $containsSpecial
Run Code Online (Sandbox Code Playgroud)
Igo*_*hov 11
您可以使用正向前瞻来创建单个正则表达式:
$strongPassword = preg_match('/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$%^&]).*$/');
// special characters ^^^^
Run Code Online (Sandbox Code Playgroud)
我在这里找到了很好的答案,并解释了确保给定字符串包含以下每个类别中至少一个字符.
小写字符,大写字符,数字,符号
^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*(_|[^\w])).+$
Run Code Online (Sandbox Code Playgroud)
一个简短的解释:
^
//字符串的开头
(?=.*[a-z])
//使用正向前看以查看是否存在至少一个小写字母
(?=.*[A-Z])
//使用正向前看以查看是否存在至少一个大写字母
(?=.*\d)
//使用正向前看以查看是否存在至少一个数字
(?=.*[_\W])
//使用正向前看以查看是否存在至少一个下划线或非单词字符
.+
//吞噬整个字符串
$
//字符串的结尾
希望对你有所帮助.
小智 5
False(上面选择的答案 - 谢谢!)有一个非常简单的方法可以让你理解它(如果你不太熟悉正则表达式)并想出适合你的方法。
我只是将其详细说明一下:
(您可以将其粘贴到http://phptester.net/index.php?lang=en来使用它)
<?php
$pass="abc1A";
$ucl = preg_match('/[A-Z]/', $pass); // Uppercase Letter
$lcl = preg_match('/[a-z]/', $pass); // Lowercase Letter
$dig = preg_match('/\d/', $pass); // Numeral
$nos = preg_match('/\W/', $pass); // Non-alpha/num characters (allows underscore)
if($ucl) {
echo "Contains upper case!<br>";
}
if($lcl) {
echo "Contains lower case!<br>";
}
if($dig) {
echo "Contains a numeral!<br>";
}
// I negated this if you want to dis-allow non-alphas/num:
if(!$nos) {
echo "Contains no Symbols!<br>";
}
if ($ucl && $lcl && $dig && !$nos) { // Negated on $nos here as well
echo "<br>All Four Pass!!!";
} else {
echo "<br>Failure...";
}
?>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
46537 次 |
最近记录: |