Finalmix6
Finalmix6

Reputation: 415

Php : generate at least one digit and one letter

How can I generate at least one digit and one letter with let's say 5 strings characters?

I know I can randomly generate digits and letters with this :

echo $rand = substr(md5(microtime()),rand(0,26),5);

However, I've just checked it, and it can appear it only gives me simply 5 letters or 5 digits, and I'd like the rand to be always mixed with at least 1 digit and 1 letter.

Upvotes: 1

Views: 557

Answers (1)

MWik
MWik

Reputation: 103

If you want to be sure that $rand contains at least 1 digit and 1 letter, add checking. And then, for example, generate until success:

while ( !preg_match('/[0-9]/', $rand) && !preg_match('[a-z]',$rand )) { $rand = substr(md5(microtime()),rand(0,26),5) };

Upvotes: 1

Related Questions