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

1
  • What have you tried so far? Where are you stuck? Commented Oct 12, 2020 at 9:39

2 Answers 2

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);
}
Sign up to request clarification or add additional context in comments.

6 Comments

I fixed a typo in there. Your function can return an empty string though, which probably isn't wanted.
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 (stackoverflow.com/a/6419126/3080207).
Sometimes it shows a blank response but basically, it works. Thank you!
@user2534787 That's what I meant by my first comment. Use mb_strlen($text) - 1 instead on the first line to prevent it.
i try this code but it's not work proper _____________________<?php echo $string = 'myawesomestring'; function getRandomSubstring($text) { $random1 = rand(0, mb_strlen($text)); $random2 = rand($random1, mb_strlen($text)); return substr($text, $random1, $random2); } $output_data = getRandomSubstring($string); echo $output_data; ?>_____________output_data in value not found blank data given.
|
-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); 
?>

2 Comments

Please add some explanation to your answer such that others can learn from it. How does this snippet use random substrings?
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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.