List of character class members

I am creating a function that I would like to generate random strings from a given character set. I would like to allow users to specify a regex character class instead of requiring them to specify each individual character.
For instance:

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

If the allowed characters are the string of all valid characters, then this is simple:

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

I would like to be able to specify valid characters like "./0-9A-Za-z" instead of "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"

+4
source share
2 answers

I have not tested, but, I think, you will understand the main idea

 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'); 
+1
source

What about:

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

exit:

 ./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz 
+2
source

Source: https://habr.com/ru/post/1403703/


All Articles