a method of selecting random characters from given string

前端 未结 15 1890
小鲜肉
小鲜肉 2020-12-03 21:53

Can anyone help me with a solution that pulls the position and value of a random character from a given string using PHP. For example I have a a string variable $string = \

相关标签:
15条回答
  • 2020-12-03 22:33

    For anyone who might want to use it for the same case like mine:

    I just wrote a simple SecretGenerator:

    echo generateSecret(10);
    
    function generateSecret($length) {
    $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789&!^§\$ß";
    $key = "";
    for($i = 0; $i <= $length; $i++){
        $key .= $chars[mt_rand(0, strlen($chars)-1)];
    }
        return $key;
    }
    

    Will return something like this: "6qß^0UoH7NP"

    Of course, this is not a secure function, but for generating simple Hashes it's quite okay to use.

    0 讨论(0)
  • 2020-12-03 22:36

    Just for fun:

    $chars = preg_split('//', $string, -1, PREG_SPLIT_NO_EMPTY);
    echo $string[array_rand($chars)];
    
    0 讨论(0)
  • 2020-12-03 22:37
    $string = 'helloworld'; 
    $pos = rand(0,(strlen($string)-1));
    echo $pos."th char is: ". $string[$pos];
    
    0 讨论(0)
提交回复
热议问题