Random\Randomizer::getBytesFromString
(PHP 8 >= 8.3.0)
Random\Randomizer::getBytesFromString — Get random bytes from a source string
Descrição
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.
Parâmetros
Valor Retornado
A string containing the requested number of random bytes taken from the input string
.
Erros/Exceções
-
If
string
is empty, a ValueError will be thrown. -
If the value of
length
is less than1
, a ValueError will be thrown. -
Qualquer erro ou exceção Throwable lançados pelo método Random\Engine::generate()
do mecanismo
Random\Randomizer::$engine
subjacente.
Exemplos
Example #1 Random\Randomizer::getBytesFromString() example
<?php
$randomizer = new \Random\Randomizer();
printf(
"%s.example.com",
$randomizer->getBytesFromString('abcdefghijklmnopqrstuvwxyz0123456789', 16)
);
?>
O exemplo acima produzirá algo semelhante a:
3zsw04eiubcf82jd.example.com
Example #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));
?>
O exemplo acima produzirá algo semelhante a:
11551-80418-27047-42075
Example #3 Select from a string with a non-uniform distribution
<?php
$randomizer = new \Random\Randomizer();
echo $randomizer->getBytesFromString('aaaaabcdef', 20);
?>
O exemplo acima produzirá algo semelhante a:
fddacbeaaeaaacaaaaca
Veja Também
- Random\Randomizer::getBytes() - Get random bytes