Reputation: 4189
I would like to extract random substrings form a string, how could I do this?
Lets say I have this text
$text = "Some totally random text I have, and I want to work on it! But need
some php skillz...";
and as a result I want an array like this with extracted substrings
$random_string[0] = "random text I have";
$random_string[1] = "I have, and I want to work";
$random_string[2] = "need some php skillz...";
Upvotes: 1
Views: 2140
Reputation: 522085
$words = explode(' ', $string);
$numWords = count($words);
echo join(' ', array_slice($words, mt_rand(0, $numWords - 1), mt_rand(1, $numWords)));
Upvotes: 4
Reputation: 16204
Create two random numbers which is less than the length of the string
$n1=rand(1, strlen($string));
$n2=rand(1, strlen($string));
Then create a sub string using $n
$new_string = substr($string, $n1, $n2)
Hope this helps
Updated:
You can do like this to get words ,
$string = "Hello Stack over Flow in here ";
The use explode
- Returns an array of strings, each of which is a substring of string
$pieces = explode(" ", $string);
$pieces will be a array of sepearte words of your string
Example :
$pieces[0] = "Hello"
$pieces[1] = "can"
Then use array_rand
— Pick one or more random entries out of an array
$rand_words = array_rand($pieces, 2);
so $rand_words
will have two random words from your string
Example :
$rand_words[0]= "Stack"
$rand_words[1]= "Over"
Upvotes: 3
Reputation: 5349
Use substr with random start and lengths.
$random_string = substr($text, rand(1, mb_strlen($text) - 20), rand(10, 20));
Adjust your values and add more logic if you need.
Upvotes: 0