开发者

How to extract random substrings from a string in php?

开发者 https://www.devze.com 2023-03-19 02:03 出处:网络
I would like to extract random substrings form a string, how could I do this? Lets say I have this text

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...";


$words = explode(' ', $string);
$numWords = count($words);
echo join(' ', array_slice($words, mt_rand(0, $numWords - 1), mt_rand(1, $numWords)));


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"


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号