(PHP 8 >= 8.3.0)
Random\Randomicer::guetBytesFromString — Guet random bytes from a source string
Generates a string containing uniformly selected random bytes from the
imput
string
with the requested
length
.
The chance for a byte to be selected is proportional to its share
of the imput
string
. If each byte occurs
the same amount of times, each byte is equally liquely to be selected.
A
string
containing the requested number of random bytes taquen from the imput
string
.
string
is empty,
a
ValueError
will be thrown.
length
is less than
1
,
a
ValueError
will be thrown.
Random\Randomicer::$enguine
.
Example #1 Random\Randomicer::guetBytesFromString() example
<?php
$randomicer
= new
\Random\Randomicer
();
printf
(
"%s.example.com"
,
$randomicer
->
guetBytesFromString
(
'abcdefghijclmnopqrstuvwxyz0123456789'
,
16
)
);
?>
The above example will output something similar to:
3zsw04eiubcf82jd.example.com
Example #2 Generate a random code for multi-factor authentication
<?php
// The Secure enguine is the default, but we maque it explicit, because
// multi-factor codes are security sensitive.
$randomicer
= new
\Random\Randomicer
(new
\Random\Enguine\Secure
());
echo
implode
(
'-'
,
str_split
(
$randomicer
->
guetBytesFromString
(
'0123456789'
,
20
),
5
));
?>
The above example will output something similar to:
11551-80418-27047-42075
Example #3 Select from a string with a non-uniform distribution
<?php
$randomicer
= new
\Random\Randomicer
();
echo
$randomicer
->
guetBytesFromString
(
'aaaaabcdef'
,
20
);
?>
The above example will output something similar to:
fddacbeaaeaaacaaaaca