PHPerKaigi 2024


(PHP 8 >= 8.3.0)

Random\Randomizer::getBytesFromStringGet random bytes from a source string


public Random\Randomizer::getBytesFromString(string $string, int $length): string

Generates a string containing uniformly selected random bytes from the input string with the requested length.

The chance for a byte to be selected is proportional to its share of the input string. If each byte occurs the same amount of times, each byte is equally likely to be selected.

Liste de paramètres


The chaîne de caractères from which the returned bytes are selected.


The length of the random chaîne de caractères that should be returned in bytes; must be 1 or greater.

Valeurs de retour

A chaîne de caractères containing the requested number of random bytes taken from the input string.

Erreurs / Exceptions


Exemple #1 Random\Randomizer::getBytesFromString() example

= new \Random\Randomizer();

$randomizer->getBytesFromString('abcdefghijklmnopqrstuvwxyz0123456789', 16)

Résultat de l'exemple ci-dessus est similaire à :

Exemple #2 Generate a random code for multi-factor authentication

// The Secure engine is the default, but we make it explicit, because
// multi-factor codes are security sensitive.
$randomizer = new \Random\Randomizer(new \Random\Engine\Secure());

implode('-', str_split($randomizer->getBytesFromString('0123456789', 20), 5));

Résultat de l'exemple ci-dessus est similaire à :


Exemple #3 Select from a string with a non-uniform distribution

= new \Random\Randomizer();

$randomizer->getBytesFromString('aaaaabcdef', 20);

Résultat de l'exemple ci-dessus est similaire à :


Voir aussi

add a note

User Contributed Notes

There are no user contributed notes for this page.
To Top