Method for selecting random characters from a given string

Can someone 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 string variable $ string = 'helloworld'; and I would like to randomly select a character from the string $ and display the character and its position.

+5
source share
15 answers
$str = 'helloworld';

$randomChar = $str[rand(0, strlen($str)-1)];

Codepad .

+20
source
$string = 'helloworld'; 
$pos = rand(0,(strlen($string)-1));
echo $pos."th char is: ". $string[$pos];
+6
source

mt_rand(),

:

$charIndex = mt_rand(0, strlen($string)-1);
$char = $string[$charIndex]; // or substr($string, $charIndex, 1)
+2
$name = "Hello";
echo $name[rand(0,strlen(substr($name,0,strlen($name)-1)))];
+2

- utf8 (), :

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);
+1

< StrLen ($ yourchain) -1;

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

0
echo substr($string, rand(0, strlen($string)-1), 1);
0

rand($x,$y), $x $y :

$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
$str = "helloworld";
$randIndex = rand(0,strlen($str));
echo $str[$randIndex]," is at $randIndex";
0

:

$chars = preg_split('//', $string, -1, PREG_SPLIT_NO_EMPTY);
echo $string[array_rand($chars)];
0
  • , ($ length)
  • ($ a = Random.get($ length))
  • , . ($ string.substring($ a, 1))

, php (java\m/)

0
$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

, :

$str = 'helloworld';

$randChar = $str[array_rand(str_split($str))];
0

:

$string    = 'helloworld';
$position  = rand(0, strlen($string));
$character = $string[$position-1];

echo $character . ' is placed ' . $position . ' in the following string: ' . $string;

:

e is placed 2 on the following line: helloworld


CodePad Demo

0
source

For those who might want to use it for the same case, such as 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 protected function, but it is quite normal to use it to generate simple hashes.

0
source

All Articles