Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

134
Views
PHP Split string output up randomly insert into array

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.

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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); 
over 4 years ago · Santiago Trujillo Report

0

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

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!