Random string generator; safe for multibyte character encodings
<?php
/*
* Generate a random, multibyte-safe string
*
* @param string $ch characters allowed in random string
* @param int $len desired length for random string
* @return string
*/
function randomString($ch, $len)
{
$arr = preg_split("/(?<!^)(?!$)/u", $ch);
for ($i=0; $i<$len; $i++)
$s .= $arr[rand(0, count($arr)-1)];
return $s;
}
randomString("UTF-8 safe▐▄█▌ ▀░▒▓符号化", 10);
// mb_string(10) "符▐█f ▒▐▒▐"
?>
“But Jules, why might you ever want to generate a random string, of arbitrary length, from a set of multibyte-encoded characters?” you ask . . . and laugh.
“Well,” I respond after noting your well punctuated dialog and somehow missing the smirk, “I’m sure I’ll think of something . . .”
Anyway . . . the real hero of the method is preg_split("/(?<!^)(?!$)/u", $ch);.
Let’s talk about UTF-8 and regular expressions . . .
. . .
. . .
Lastly, when working with multibyte characters, don’t forget to encode your output! (>_<)
header("Content-type: text/html; charset=UTF-8"); or <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> should do the trick!