开发者

PHP Check For One Letter and One Digit

开发者 https://www.devze.com 2023-04-01 13:09 出处:网络
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.

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
$stri开发者_Go百科ng = '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." );


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 ... }
0

精彩评论

暂无评论...
验证码 换一张
取 消