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

141
Views
La salida de cadena dividida de PHP se inserta aleatoriamente en la matriz

Estoy tratando de encontrar la mejor manera de dividir una cadena al azar.

Ejemplo :

 $variable1 = "this_is_the_string_contents";

El resultado que estoy tratando de lograr es este.

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

Cuál es la mejor manera de hacer esto. No tengo idea de qué función(es) PHP sería(n) más adecuada(s) para la tarea que he estado buscando, una combinación de, foreach(), rand(), etc.

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Esto dividirá una cadena en una matriz de subcadenas de longitud aleatoria.

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

Esto será totalmente aleatorio, por lo que podría terminar con una matriz como

 ["this_is_the_string_content","s"]

en lugar del ejemplo distribuido más uniformemente que mostraste. Si desea evitar eso, puede "desaleatorizar" un poco la parte de longitud aleatoria.

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

Eso evitará que las subcadenas consuman más de la mitad de la cadena, hasta que desaparezca la mitad de la cadena.


Después de tener la matriz de subcadenas, también puede aleatorizarla con

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

Puede usar rand() para generar un número aleatorio para el tamaño de fragmento si lo desea. Dependiendo de lo que intente hacer, podría valer la pena considerar eliminar espacios/guiones bajos.

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!