Random\Randomizer::getBytesFromString

(PHP 8 >= 8.3.0)

Random\Randomizer::getBytesFromString β€” Get 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.

ΠŸΠ°Ρ€Π°ΠΌΠ΅Ρ‚Ρ€ΠΈ

string

The string from which the returned bytes are selected.

length

The length of the random string that should be returned in bytes; must be 1 or greater.

ЗначСння, Ρ‰ΠΎ ΠΏΠΎΠ²Π΅Ρ€Ρ‚Π°ΡŽΡ‚ΡŒΡΡ

A string containing the requested number of random bytes taken from the input string.

Помилки/Π²ΠΈΠΊΠ»ΡŽΡ‡Π΅Π½Π½Ρ

  • If string is empty, a ValueError will be thrown.
  • If the value of length is less than 1, a ValueError will be thrown.
  • Π‘ΡƒΠ΄ΡŒ-який Π½Π°Ρ‰Π°Π΄ΠΎΠΊ класу Throwable, Ρ‰ΠΎ Π²ΠΈΠΊΠΈΠ΄Π°Ρ”Ρ‚ΡŒΡΡ ΠΌΠ΅Ρ‚ΠΎΠ΄ΠΎΠΌ Random\Engine::generate() основного Ρ€ΡƒΡˆΡ–Ρ Random\Randomizer::$engine.

ΠŸΡ€ΠΈΠΊΠ»Π°Π΄ΠΈ

ΠŸΡ€ΠΈΠΊΠ»Π°Π΄ #1 Random\Randomizer::getBytesFromString() example

<?php
$randomizer
= new \Random\Randomizer();

printf(
"%s.example.com",
$randomizer->getBytesFromString('abcdefghijklmnopqrstuvwxyz0123456789', 16)
);
?>

Поданий Π²ΠΈΡ‰Π΅ ΠΏΡ€ΠΈΠΊΠ»Π°Π΄ Π²ΠΈΠ²Π΅Π΄Π΅ Ρ‰ΠΎΡΡŒ схоТС Π½Π°:

3zsw04eiubcf82jd.example.com

ΠŸΡ€ΠΈΠΊΠ»Π°Π΄ #2 Generate a random code for multi-factor authentication

<?php
// 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());

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

Поданий Π²ΠΈΡ‰Π΅ ΠΏΡ€ΠΈΠΊΠ»Π°Π΄ Π²ΠΈΠ²Π΅Π΄Π΅ Ρ‰ΠΎΡΡŒ схоТС Π½Π°:

11551-80418-27047-42075

ΠŸΡ€ΠΈΠΊΠ»Π°Π΄ #3 Select from a string with a non-uniform distribution

<?php
$randomizer
= new \Random\Randomizer();

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

Поданий Π²ΠΈΡ‰Π΅ ΠΏΡ€ΠΈΠΊΠ»Π°Π΄ Π²ΠΈΠ²Π΅Π΄Π΅ Ρ‰ΠΎΡΡŒ схоТС Π½Π°:

fddacbeaaeaaacaaaaca

ΠŸΡ€ΠΎΠ³Π»ΡΠ½ΡŒΡ‚Π΅ Ρ‚Π°ΠΊΠΎΠΆ

οΌ‹add a note

User Contributed Notes

There are no user contributed notes for this page.