Skip to content
Advertisement

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

Advertisement

Answer

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);
}
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement