2

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

user2534787
  • 115
  • 1
  • 7

2 Answers2

3

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);
}
Jeto
  • 14,596
  • 2
  • 32
  • 46
  • I fixed a typo in there. Your function can return an empty string though, which probably isn't wanted. – Jeto Oct 12 '20 at 04:48
  • This works - OP may want to run this in a loop to match their desired output (multiple instances on the same line). Also worth noting not everyone may have mb_strlen available (https://stackoverflow.com/a/6419126/3080207). – mikey Oct 12 '20 at 04:52
  • Sometimes it shows a blank response but basically, it works. Thank you! – user2534787 Oct 12 '20 at 04:55
  • @user2534787 That's what I meant by my first comment. Use `mb_strlen($text) - 1` instead on the first line to prevent it. – Jeto Oct 12 '20 at 04:58
  • i try this code but it's not work proper __________________________________output_data in value not found blank data given. – JD Savaj Oct 12 '20 at 10:31
  • There is no regular distribution here. You have more chance to have end characters appearing than beginning characters. To have regular distribution, you need to roll the both randoms from 0 to maximum length. Then keep the lowest at second argument for `substr` and use the absolute substract of the two values for the third argument for `substr` – SeeoX Oct 12 '20 at 11:53
-2

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); 
?>
JD Savaj
  • 803
  • 8
  • 16
  • 1
    Please add some explanation to your answer such that others can learn from it. How does this snippet use random substrings? – Nico Haase Oct 12 '20 at 09:39
  • Can you explain what that code does? When I execute it, it shows only a pretty limited amount of substrings, and they never share the same letters in the front (like in the example in the question) – Nico Haase Oct 12 '20 at 09:54