1

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...";
2
  • You mean you dont have any conditions on when or how a sub-string must be made?? Commented Jul 11, 2011 at 4:37
  • Thanks for the comment, one condition is to cut off at white space, so the script wont cut words in their middle. Commented Jul 11, 2011 at 4:50

3 Answers 3

4
$words = explode(' ', $string);
$numWords = count($words);
echo join(' ', array_slice($words, mt_rand(0, $numWords - 1), mt_rand(1, $numWords)));
Sign up to request clarification or add additional context in comments.

Comments

3

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"

4 Comments

Appreciated Sudantha, how could I modify this to cutoff only at whitespace?
@giorgio79 - can u post a example here?
Sure, so if we have this $text = "Some totally random text I have, and I want to work on it! But need some php skillz..."; I think your solution would extract sg like this as well "ally rand" however I want cutoffs to always be at whitespace, so it should be "totally random"
ill check on this giime few mins
0

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.

3 Comments

Appreciated Blair, how could I modify this to cutoff only at whitespace?
this is not 100% correct what happen if the random number is > length of the string ? it will always gives the full string
I know, I didn't have the time to write a full example, that's why I had the final line of text there. deceze has the better method anyway.

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.