a method of selecting random characters from given string

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

    Code:

    $string    = 'helloworld';
    $position  = rand(0, strlen($string));
    $character = $string[$position-1];
    
    echo $character . ' is placed ' . $position . ' in the following string: ' . $string;
    

    Output Example:

    e is placed 2 in the following string: helloworld


    CodePad Demo

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

    Using mt_rand(),

    You can get the index of a random character by:

    $charIndex = mt_rand(0, strlen($string)-1);
    $char = $string[$charIndex]; // or substr($string, $charIndex, 1)
    
    0 讨论(0)
  • 2020-12-03 22:26
    $string = 'helloworld';
    
    //generate a random position between 0 and string length ( note the -1 )
    $randPos = mt_rand(0, strlen($string)-1);
    
    echo 'Position : ' . $randPos . "\n";
    echo 'Character : ' . $string[$randPos] . "\n";
    
    0 讨论(0)
  • 2020-12-03 22:27
    $str = 'helloworld';
    
    $randomChar = $str[rand(0, strlen($str)-1)];
    

    CodePad.

    0 讨论(0)
  • 2020-12-03 22:28
    $name = "Hello";
    echo $name[rand(0,strlen(substr($name,0,strlen($name)-1)))];
    
    0 讨论(0)
  • 2020-12-03 22:28

    You can use the rand($x,$y) function which returns a random number between $x and $y inclusive:

    $str = 'helloworld';
    
    // get a random index between 0 and the last valid index
    $rand_pos = rand(0,strlen($str)-1);
    
    // access the char at the random index.
    $rand_chr = $str[$rand_pos];
    
    0 讨论(0)
提交回复
热议问题