优化功能在PHP中创建一个随机的UTF-8字符串? (仅字母字符)(Optimal functi

2019-09-17 14:25发布

我写了这个功能,创建UTF-8字符的随机字符串。 它运作良好,但正则表达式[^\p{L}]未过滤似乎所有的非字母字符。 我想不出更好的方式来产生全方位的Unicode没有非字母字符..短的手动搜索和确定65和65533之间的小数信范围。

function rand_str($max_length, $min_length = 1, $utf8 = true) {
    static $utf8_chars = array();

    if ($utf8 && !$utf8_chars) {
        for ($i = 1; $i <= 65533; $i++) {
            $utf8_chars[] = mb_convert_encoding("&#$i;", 'UTF-8', 'HTML-ENTITIES');
        }

        $utf8_chars = preg_replace('/[^\p{L}]/u', '', $utf8_chars);

        foreach ($utf8_chars as $i => $char) {
            if (trim($utf8_chars[$i])) {
                $chars[] = $char;
            }
        }

        $utf8_chars = $chars;
    }

    $chars = $utf8 ? $utf8_chars : str_split('abcdefghijklmnopqrstuvwxyz');
    $num_chars = count($chars);
    $string = '';

    $length = mt_rand($min_length, $max_length);

    for ($i = 0; $i < $length; $i++) {
        $string .= $chars[mt_rand(1, $num_chars) - 1];
    }

    return $string;
}

Answer 1:

\p{L}可能赶上太多。 尝试限制到{的L1}和{} LU - {L} {包括罗} - 别人。



Answer 2:

随着PHP7和IntlChar现在有一个更好的办法:

function utf8_random_string(int $length) : string {
        $r = "";

        for ($i = 0; $i < $length; $i++) {
            $codePoint = mt_rand(0x80, 0xffff);
            $char = \IntlChar::chr($codePoint);
            if ($char !== null && \IntlChar::isprint($char)) {
                $r .= $char;
            } else {
                $i--;
            }
        }

        return $r;
    }


文章来源: Optimal function to create a random UTF-8 string in PHP? (letter characters only)