a method of selecting random characters from given string

前端 未结 15 1888
小鲜肉
小鲜肉 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:12

    Since noone mentinoned any utf8 (multibyte) safe method, here is mine:

    mb_internal_encoding("UTF-8");
    $possible="aábcdeéfghiíjklmnoóöópqrstuúüűvwxyzAÁBCDEÉFGHIÍJKLMNOÓÖŐPQRSTUÚVWXYZ";
    $char=mb_substr($possible,rand(0, mb_strlen($possible) - 1),1);
    
    0 讨论(0)
  • 2020-12-03 22:13

    First choose a random number < strlen($yourchain)-1;

    Then substr($yourchain,$random,$random+1);

    0 讨论(0)
  • 2020-12-03 22:13
    1. find the length of the string , ($length)
    2. use random function to generate random value within that range , ($a=Random.get($length))
    3. use substring function to get the value of the random position.($string.substring($a,1))

    sorry i dont know syntax for php (java \m/)

    0 讨论(0)
  • 2020-12-03 22:18
    $str = "helloworld";
    $randIndex = rand(0,strlen($str));
    echo $str[$randIndex]," is at $randIndex";
    
    0 讨论(0)
  • 2020-12-03 22:18

    More internal overhead, but easy to read:

    $str = 'helloworld';
    
    $randChar = $str[array_rand(str_split($str))];
    
    0 讨论(0)
  • 2020-12-03 22:20
    echo substr($string, rand(0, strlen($string)-1), 1);
    
    0 讨论(0)
提交回复
热议问题