If you want to do this in a regular manner and based on the use case that you have provided, we need to make the entire regular expression complementary. We will also use capture groups in our forecasts.
But first, create a regex:
[\d]
is redundant, just use \d
.\S*(?=\S{8,})
delete the part \S*
, we already have it at the end.
Our regular expression will look like ^(?=\S{8,})(?=\S*[az])(?=\S*[AZ])(?=\S*\d)\S*$
Now this is the hard part, we will add groups to our views and make them optional:
^(?=(\S{8,})?)(?=(\S*[az])?)(?=(\S*[AZ])?)(?=(\S*\d)?)\S*$
You may ask why? Groups are created so that we can track them later. We make them optional so that our regular expression always matches. So we can do some math!
$regex = '~^(?=(\S{8,})?)(?=(\S*[az])?)(?=(\S*[AZ])?)(?=(\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
Hamza source share