编写一个函数Ge​​neratePassword,它接受两个参数,一个整数和一个由字母(a-z)和数字(0-9)组成的字符串

时间:2012-04-03 18:35:26

标签: php

编写一个函数GeneratePassword,它接受​​两个参数,一个整数和一个由字母(a-z)和数字(0-9)组成的字符串。

当调用GeneratePassword(5,'abc0123')时,它应该返回一个从'abc0123'取得的5个字符的随机字符串。

例如:GeneratePassword(7,'abczxc012394')可以返回以下任何输出:

  

2c00acb
  2c23z93
  030b2a4

1 个答案:

答案 0 :(得分:3)

我认为你正在寻找标签。

本着帮助他人的精神,我会发布评论解决方案。但是,请记住,改善的唯一方法是先尝试,稍后再提问。也就是说,尝试然后问别人你哪里出错了。

实施例/ Demo

/**
 * Generate a password N characters long consisting of characters
 *
 * @param int $size
 * @param string $characters
 * @param callback $random (optional) source of random, a function with two parameters, from and to
 * @return string|NULL password
 */
function generate_password($size, $characters, $random = 'rand') {

    // validate $size input
    $size = (int) $size;

    if ($size <= 0) {
        trigger_error(sprintf('Can not create a password of size %d. [%s]', $size, __FUNCTION__), E_USER_WARNING);
        return NULL;
    }

    if ($size > 255) {
        trigger_error(sprintf('Refused to create a password of size %d as this is larger than 255. [%s]', $size, __FUNCTION__), E_USER_WARNING);
        return NULL;
    }

    // normalize $characters input, remove duplicate characters
    $characters = count_chars($characters, 3);

    // validate number of characters
    $length = strlen($characters);
    if ($length < 1) {
        trigger_error(sprintf('Can not create a random password out of %d character(s). [%s]', $length, __FUNCTION__), E_USER_WARNING);
        return NULL;
    }

    // initialize the password result
    $password = str_repeat("\x00", $size);

    // get the number of characters minus one
    // your string of characters actually begins at 0 and ends on the
    // string-length - 1:
    //   $characters[0] = 'a'
    //   $characters[1] = 'b'
    //   $characters[2] = 'c'
    $length--;

    // get one random character per each place in the password
    while ($size--)
    {
        // generate a random number between 0 and $length (including)
        $randomValue = $random(0, $length);
        // that random number is used to turn the number into a character
        $character = $characters[$randomValue];
        // set the random character
        $password[$size] = $character;
    }

    // return the result
    return $password;
}