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