Reputation: 14008
Hi I need to use php's pregmatch to check a string is valid. In order to be valid the string needs to have at least one uppercase character, at least one lowercase character, and then at least one symbol or number
thanks
Upvotes: 4
Views: 8282
Reputation: 3068
If you want these not to be necessarily in order, you need a lookahead. The following expression will validate for at least one lower char, one upper char and one number:
$result = preg_match('^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])', $string);
You can put a lot of special chars with the numbers, like this:
$result = preg_match('^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9$%])', $string);
Upvotes: 0
Reputation: 92976
You can achieve this by using lookaheads
^(?=.*[a-z])(?=.*[A-Z])(?=.*[\d,.;:]).+$
See it here on Regexr
A lookahead is a zero width assertion, that means it does not match characters, it checks from its position if the assertion stated is true. All assertions are evaluated separately, so the characters can be in any order.
^
Matches the start of the string
(?=.*[a-z])
checks if somewhere in the string is a lowercase character
(?=.*[A-Z])
checks if somewhere in the string is a uppercase character
(?=.*[\d,.;:])
checks if somewhere in the string is a digit or one of the other characters, add those you want.
.+$
Matches the string till the end of the string
As soon as one of the Assertions fail, the complete regex fail.
Upvotes: 7
Reputation: 138
If the match has to be in the order you've described, you could use
$result = preg_match('/[A-Z]+[a-z]+[\d!$%^&]+/', $string);
If the characters can be in any order I'm not so sure, without doing three separate checks like so:
$result = (preg_match('/[A-Z]+/', $string) && preg_match('/[a-z]+/', $string) && preg_match('/[\d!$%^&]+/', $string));
As people have pointed out below, you can do this all in one regular expression with lookaheads.
Upvotes: 3
Reputation: 663
According to your request:
[A-Z]+
Match any uppercase char
[a-z]+
Match any lowercase char
[\d§$%&]+
Match a number or special chars (add more special if you need to)
The result would look like this: [A-Z]+[a-z]+[\d§$%&]+
This isn't ideal though. You might want to check Regexr and try what kind of regex fits your requirements.
Upvotes: 0