基本上,我只是想知道是否存在这样的函数:
$string = 'helloWorld';
// 1 uppercase, 1 lower case, 1 number and at least 8 of length
$regex = '/^\S*(?=\S{8,})(?=\S*[a-z])(?=\S*[A-Z])(?=\S*[\d])\S*$/'
$percent = matchPercent($string, $regex);
echo "the string match {$percent}% of the given regex";
然后,结果可能是这样的:
字符串与给定正则表达式的 75% 匹配
看到另一个帖子和问题,我可以这样做:
$uppercase = preg_match('@[A-Z]@', $password);
$lowercase = preg_match('@[a-z]@', $password);
$number = preg_match('@[0-9]@', $password);
但是,目标是在函数中使用任何正则表达式模式
如果您想以正则表达式的方式并根据您提供的用例来执行此操作,我们需要将整个正则表达式设置为可选。此外,我们将在前瞻中使用捕获组。
但首先,让我们改进你的正则表达式:
-
[\d]
是多余的,只需使用\d
.
-
\S*(?=\S{8,})
remove \S*
部分,我们已经在最后了。
我们的正则表达式看起来像^(?=\S{8,})(?=\S*[a-z])(?=\S*[A-Z])(?=\S*\d)\S*$
现在是棘手的部分,我们将在前瞻中添加组并使它们可选:
^(?=(\S{8,})?)(?=(\S*[a-z])?)(?=(\S*[A-Z])?)(?=(\S*\d)?)\S*$
你可能会问为什么?这些组是为了我们以后可以跟踪它们而创建的。我们将它们设为可选,以便我们的正则表达式始终匹配。这样,我们就可以做一些数学题了!
$regex = '~^(?=(\S{8,})?)(?=(\S*[a-z])?)(?=(\S*[A-Z])?)(?=(\S*\d)?)\S*$~';
$input = 'helloWorld';
preg_match_all($regex, $input, $m);
array_shift($m); // Get rid of group 0
for($i = 0, $j = $k = count($m); $i < $j; $i++){ // Looping
if(empty($m[$i][0])){ // If there was no match for that particular group
$k--;
}
}
$percentage = round(($k / $j) * 100);
echo $percentage;
Online php demo https://eval.in/144753
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)