Justin
Justin

Reputation: 45330

PHP Check For One Letter and One Digit

How can I check if a string is at least one letter and one digit in PHP? Can have special characters, but basically needs to have one letter and one digit.

Examples:

$string = 'abcd'   //Return false
$string = 'a3bq'   //Return true
$string = 'abc#'   //Return false
$string = 'a4#e'   //Return true

Thanks.

Upvotes: 1

Views: 3307

Answers (4)

ShaneC
ShaneC

Reputation: 2406

The pattern you're looking for is ^.*(?=.*\d)(?=.*[a-zA-Z]).*$

In use:

if( preg_match( "/.*(?=.*\d)(?=.*[a-zA-Z]).*/", $string ) )
     echo( "Valid" );
else
     echo( "Invalid." );

Upvotes: 0

Phil
Phil

Reputation: 164736

Try this

if (preg_match('/[A-Za-z]/', $string) & preg_match('/\d/', $string) == 1) {
    // string contains at least one letter and one number
}

Upvotes: 6

ikegami
ikegami

Reputation: 385590

preg_match('/\pL/', $string) && preg_match('/\p{Nd}/', $string)

or

preg_match('/\pL.*\p{Nd}|\p{Nd}.*\pL/', $string)

or

preg_match('/^(?=.*\pL)(?=.*\p{Nd})/', $string)

or

preg_match('/^(?=.*\pL).*\p{Nd}/', $string)

I'm not sure if \d is equivalent to [0-9] or if it matches decimal digits in PHP, so I didn't use it. Use whichever of \d, [0-9] and \p{Nd} that matches that right thing.

Upvotes: 2

zergussino
zergussino

Reputation: 821

That should work if latin chars only and numbers:

if (preg_match('/[a-z0-9]+/i', $search_string)) { ... has at least one a-zA-Z0-9 ... }

Upvotes: -1

Related Questions