I am currently writing a small script that checks the contents of each string.
I was wondering what the REGEX would be to make sure that a string has a letter (upper or lower), a digit, and a special character?
Here is what I know so far (whcih isn't much):
if(preg_match('/^[a-zA-Z0-9]+$/i', $string)):
Help would be great!
Thank You!
To check if a string contains special characters, call the test() method on a regular expression that matches any special character. The test method will return true if the string contains at least 1 special character and false otherwise.
To check if a string contains at least one number using regex, you can use the \d regular expression character class in JavaScript. The \d character class is the simplest way to match numbers.
PHP – How to check if String contains Number(s)?ctype_digit() function returns true if the string passed to it has digits for all of its characters, else it returns false.
The easiest (and probably best) way is to do three separate checks with 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With