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.
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);
$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.