Here's one way to randomly place a number of varying length into a PHP string:
$numbers = array(
1 => 1, // 1-digit number
42 => 2, // 2-digit number
100 => 3, // 3-digit number
// ...
);
$num_inserts = rand(1, 5); // insert 1-5 numbers
$insert_values = array_rand($numbers, $num_inserts);
$string = "This is a string with some random positions for numbers.";
foreach ($insert_values as $value) {
$length = $numbers[$value];
$position = rand(0, strlen($string)-$length);
$string = substr($string, 0, $position) . $value . substr($string, $position+$length);
}
This code selects a random position in the string for each insertion, ensuring that they don't overlap. You can adjust the $num_inserts and $numbers arrays to suit your needs.
Asked: 2022-02-20 11:00:00 +0000
Seen: 8 times
Last updated: Nov 17 '21