Ask Your Question
3

How can I randomly place a number of varying length into a PHP string?

asked 2022-02-20 11:00:00 +0000

scrum gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2021-11-17 11:00:00 +0000

pufferfish gravatar image

Here's one way to randomly place a number of varying length into a PHP string:

  1. Define an array of possible numbers and their lengths:
$numbers = array(
    1 => 1, // 1-digit number
    42 => 2, // 2-digit number
    100 => 3, // 3-digit number
    // ...
);
  1. Decide how many numbers you want to insert and generate a random array of their values:
$num_inserts = rand(1, 5); // insert 1-5 numbers
$insert_values = array_rand($numbers, $num_inserts);
  1. Loop through the insert values and insert them at random positions in the string:
$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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-02-20 11:00:00 +0000

Seen: 8 times

Last updated: Nov 17 '21