Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if string has at least one letter, number and special character in php

Tags:

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!

like image 404
Peter Stuart Avatar asked Mar 06 '12 16:03

Peter Stuart


People also ask

How do you check if a string has at least one special character?

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.

How do you check if a string contains at least one number?

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.

How do I check if a string contains numbers in PHP?

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.


1 Answers

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
like image 61
Ry- Avatar answered Oct 12 '22 03:10

Ry-