Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/234.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 列出字符类的成员_Php_Regex - Fatal编程技术网

Php 列出字符类的成员

Php 列出字符类的成员,php,regex,Php,Regex,我正在创建一个函数,我想从给定的字符集生成随机字符串。我希望允许用户指定正则表达式字符类,而不是要求他们指定每个字符。 例如: function a($length, $allowed_chars){ for ($i = 0, $salt = ""; $i < $length; $i++){ $salt .= __GET_ONE_RANDOM_CHAR_FROM_ALLOWED_CHARS__; } } 我希望能够像这样指定允许的字符“/0-9A-Za-z

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

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

我希望能够像这样指定允许的字符
“/0-9A-Za-z”
,而不是
”/0123456789abcdefghijklmnopqrstuvwxyzabefghijklmnopqrstuvxyz“

我没有检查,但我想你们会理解主要思想的

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');
函数a($length,$allowed\u chars){
$allowedCharsList=join(“”,数组_merge(范围(chr(0x1f),chr(0x23)),范围(chr(0x25),chr(0x80));//除“$”之外的所有可打印(ascii)字符
$allowed_chars=preg_replace(“/[^$allowed_chars]/”,“”,$allowedchars列表);
对于($i=0,$salt=”“;$i<$length;$i++){
$salt.=$allowed_chars{mt_rand(0,strlen($allowed_chars)-1)};
}
退还$salt;
}
回声a(10,'0-9h-w');
那么:

// 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

这恰恰相反。它从
$allowedCharsList
中删除
$userList
中的所有内容。这要求我首先列出所有可能的字符(包括用于编码的所有可打印字符)。我也希望避免这种情况,我将其更改为
join(“”,array_merge(range(chr(0x1f),chr(0x23)),range(chr(0x25),chr(0x80))因为“$”在这些盐中无效(因为它是分隔符)
./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz