1

I am trying to find the best way to split a string up randomly.

Example :

$variable1 = "this_is_the_string_contents";

The output I am trying to achieve is this.

"is"
"this"
"ents"
"cont"
"_"
etc
etc

What is the best way to do this. I have no idea what PHP function(s) would be most suited to the task I have been looking at a mix of, foreach(), rand() etc.

1
  • Maybe try using chunk_split and rand, strlen and friends. Commented Apr 29, 2017 at 1:24

3 Answers 3

3

This will break a string down into an array of random length substrings.

$l = strlen($variable1);
$i = 0;                                       // holds the current string position

while ($i < $l) {
    $r = rand(1, $l - $i);                    // get a random length for the next substring
    $chunks[] = substr($variable1, $i, $r);   // add the substring to the array
    $i += $r;                                 // increment $i by the substring length
}

This will be totally random, so you could end up with an array like

["this_is_the_string_content","s"]

instead of the more evenly distributed example you showed. If you want to avoid that, you could "de-randomize" the random length part a bit.

if ($l - $i > $i) {
    $r = rand(1, ($l - $i) / 2);
} else {
    $r = rand(1, $l - $i);        
}

That will prevent substrings from consuming more than half of the string, until half of the string is gone.


After you have the array of substrings, you can randomize it as well with

shuffle($chunks); 
Sign up to request clarification or add additional context in comments.

1 Comment

Thank's for the help I marked your answer as the solution :) Also @EdCottrell your answer before it was removed this website is super useful 3v4l.org/cRicH So thanks also for sharing a demo link.
1
$str = "this_is_the_string_contents";
$stringPiece = str_split($str, 4); //put in whatever number here for chunk size
print_r($stringPiece);

You can use rand() to generate a random number for chunk size if you wish. Depending on what you are trying to do, it might be worth considering removing spaces/underscores.

Comments

0

This can be easily achieved with the generator. The following code splits the string into a random string of between one and five characters in length.

<?php

$mystring = 'abcdefghchijklmnopqrstuvwxyz123456789';

function chunks($string, int $chunk = 5) {
    while (strlen($string) > $chunk) {
        $len = rand(1, $chunk);
        yield substr($string, 0, $len);
        $string = substr($string, $len);
    }
    yield $string; // end of the string
}

$output = iterator_to_array(chunks($mystring, 10));
var_dump($output);

Check demo code

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.