Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

140
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda