Optimal function to create a random UTF-8 string in PHP? (letter characters only)

心已入冬 提交于 2020-02-02 16:32:51

问题


I wrote this function that creates a random string of UTF-8 characters. It works well, but the regular expression [^\p{L}] is not filtering all non-letter characters it seems. I can't think of a better way to generate the full range of unicode without non-letter characters.. short of manually searching for and defining the decimal letter ranges between 65 and 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;
}

回答1:


\p{L} might be catching too much. Try to limit to {Ll} and {LU} -- {L} includes {Lo} -- others.




回答2:


With PHP7 and IntlChar there is now a better way:

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;
    }


来源:https://stackoverflow.com/questions/10793582/optimal-function-to-create-a-random-utf-8-string-in-php-letter-characters-only

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!