列出角色类的成员

时间:2012-03-27 15:56:23

标签: php regex

我正在创建一个函数,我想从给定的字符集生成随机字符串。我想允许用户指定一个正则表达式字符类,而不是要求它们指定每个字符 例如:

function a($length, $allowed_chars){
    for ($i = 0, $salt = ""; $i < $length; $i++){
        $salt .= __GET_ONE_RANDOM_CHAR_FROM_ALLOWED_CHARS__;
    }
}

如果允许的字符是所有允许字符的字符串,那么这很简单:

$characterList{mt_rand(0,strlen($characterList)-1)};

我希望能够指定允许的字符,例如"./0-9A-Za-z"而不是"./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"

2 个答案:

答案 0 :(得分:2)

怎么样:

// build a string with all printable char
$str = join('', range(' ','~'));
// define allowed char
$allowedChar = './a-zA-Z0-9';
// replace all non-allowed char by nothing, preg_quote escapes regex char
$str = preg_replace("~[^".preg_quote($allowedChar)."]~", "", $str);
echo $str,"\n";

<强>输出:

./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz

答案 1 :(得分:1)

我没有检查,但我认为你会理解主要想法

function a($length, $allowed_chars){

    $allowedCharsList = join('', array_merge(range(chr(0x1f), chr(0x23)), range(chr(0x25), chr(0x80)) )); //all printable (ascii) characters except '$'
    $allowed_chars = preg_replace("/[^$allowed_chars]/", '', $allowedCharsList);
    for ($i = 0, $salt = ""; $i < $length; $i++){
        $salt .= $allowed_chars{mt_rand(0,strlen($allowed_chars)-1)};
    }

    return $salt;
}


echo a(10, '0-9h-w');