简体   繁体   中英

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.

Try this

if (preg_match('/[A-Za-z]/', $string) & preg_match('/\d/', $string) == 1) {
    // string contains at least one letter and one number
}
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.

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." );

如果仅使用拉丁字符和数字,那应该可以工作:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM