php - Regular expression question
I want to generate a random password that has the fo开发者_如何学编程llowing pattern:
Capital, small, number, dash, capital, small, number, special charachter.
Example:
Ab1-Cd2$
I have put all the special characters in an array that I randomly pick, so I have that part figured out. But I have no clue of how to do the other part. Any suggestion?
this is not the best way, but this will work
<?php
$capital = range ('A','Z');
$small = range ('a','z');
$number = range ('0','9');
$special = array ("#","$","@");
$password = $capital[array_rand($capital)] .
$small[array_rand($small)] .
$number[array_rand($number)] .
"-" .
$capital[array_rand($capital)] .
$small[array_rand($small)] .
$number[array_rand($number)] .
$special[array_rand($special)];
print $password;
You can read about the functions i used here
array_rand
range
Will produce results like:
Tg8-Im1$
Yj3-Xl3@
Cr1-Lv1@
which i guess is your requirement
Please let me know if you want any more help on this.
Use chr()
together with a random ascii value out of the range of A-Z, a-b, 0-9.
chr here: http://php.net/manual/en/function.chr.php
ASCII table here: http://www.asciitable.com/
Example: a-z is from 97 to 122.
You don't need to use regex here. You need an array with values of all possible chars that may appear in the password. Then you simply loop over that array and take random key from it.
$chars = array('a', 'b', 'c'); // For example.
$length = 6;
$password = '';
$count = count($chars) - 1;
for ($i = 0; $i < $length; ++$i) {
$password .= $chars[mt_rand(0, $count)];
}
echo $password;
Edit:
There's a neat trick if you need values that are somehow in range. You can use range() function.
For example, here are that function, plus, chr() function to get ASCII chars (from 0x20 to 0x7E).
$chars = range(chr(32), chr(126));
精彩评论