简体   繁体   中英

php - Regular expression question

I want to generate a random password that has the following 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 AZ, ab, 0-9.

chr here: http://php.net/manual/en/function.chr.php

ASCII table here: http://www.asciitable.com/

Example: az 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));

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