mssadewa
mssadewa

Reputation: 112

limit string in preg_match on php

Thanks for visit or just see my question.
I try to catch some pattern in string on php.

pattern :
min char = 100
max char = 100
contains [a-z] and [A-Z] and [0-9] and "#" and "-" and "=" and "+"

It's return TRUE if all on pattern match and founds in string.
else it will return FALSE.

$string = "jhJH#KJNkj-HJV=+0ksdbscasdJNKajcajnacakjBKBKjbidcubiISABUIhsdbchdsiweucIBHbhbHBUJHBjhJHBIYBHBCwJHBdcd";
if (preg_match("/^.*(?=.{100,100})(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[#])(?=.*[-])(?=.*[=])(?=.*[+]).*$/", $string)){
    $result1 = true;    
} else {
    $result1 = false;
}

This works if the 100 char, But this is return TRUE too if the string length more than 100 digits.
I want return TRUE if string length not below 100 digits and not more than 100 digits and it should be contains a pattern.
Maybe any suggestions, in the pattern?

Thanks in advances

Upvotes: 1

Views: 359

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626738

You failed to actually set the min and max length as you allow 0+ any chars other than a newline before actually requiring 100 chars in the string. You need to use

'/^(?=\D*\d)(?=[^a-z]*[a-z])(?=[^A-Z]*[A-Z])(?=[^#]*#)(?=[^-]*-)(?=[^=]*=)(?=[^+]*[+]).{0,100}$/s'
                                                                                       ^^^^^^^

Here, the pattern will match 0 to 100 any chars incl. a newline (as /s allows . to match a newline) and requiring at least 1 digit, 1 lowercase, 1 uppercase, 1 #, 1-, 1 = and one +.

Actually, there are 7 conditions with specific requirements, so in fact, the minimum will be 7 chars. You need to adjust this pattern to what you really need.

Upvotes: 3

Related Questions