user2534787
user2534787

Reputation: 115

How to extract random substring from a string in php?

I would like to extract random substrings form a string, how could I do this?

Let's say I have this string as one word:

$string = "myawesomestring";

and as an output I want an random response like this with extracted substrings

myaweso myawe somestr

Upvotes: 2

Views: 132

Answers (2)

JD Savaj
JD Savaj

Reputation: 813

Try this code:

<?php
      $str = "myawesomestring";
      $l = strlen($str);
      $i = 0;                                 
      while ($i < $l) {
          $r = rand(1, $l - $i);              
          $chunks[] = substr($str, $i, $r);   
          $i += $r;                           
      }
      echo "<pre>";
      print_r($chunks); 
?>

Upvotes: -2

Elias Kleppinger
Elias Kleppinger

Reputation: 140

You need the length of the string, and, of course a random number.

function getRandomSubstring($text) {
  $random1 = rand(0, mb_strlen($text));
  $random2 = rand($random1, mb_strlen($text));
  return substr($text, $random1, $random2);
}

Upvotes: 3

Related Questions