如何从PHP中的字符串中提取随机子字符串?

发布于 2024-11-19 06:44:37 字数 328 浏览 0 评论 0原文

我想从字符串中提取随机子字符串,我该怎么做?

假设我有这个文本

$text =“我有一些完全随机的文本,我想对其进行处理!但是需要 一些 php 技能...";

因此我想要一个像这样的带有提取子字符串的数组

$random_string[0] = "random text I have";

$random_string[1] = "I have, and I want to work";

$random_string[2] = "need some php skillz...";

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

金兰素衣 2024-11-26 06:44:37
$words = explode(' ', $string);
$numWords = count($words);
echo join(' ', array_slice($words, mt_rand(0, $numWords - 1), mt_rand(1, $numWords)));
$words = explode(' ', $string);
$numWords = count($words);
echo join(' ', array_slice($words, mt_rand(0, $numWords - 1), mt_rand(1, $numWords)));
路弥 2024-11-26 06:44:37

创建小于字符串长度的两个随机数

$n1=rand(1, strlen($string));
$n2=rand(1, strlen($string));

然后使用$n创建子字符串

$new_string = substr($string, $n1, $n2)

希望这有帮助


更新:

你可以这样做像这样获取单词,

$string = "Hello Stack over Flow in here ";

使用 explode - 返回一个字符串数组,每个字符串都是字符串的子字符串

$pieces = explode(" ", $string);

$pieces 将是字符串的独立单词数组

示例:

$pieces[0] = "Hello"
$pieces[1] = "can"

然后使用array_rand - 从数组中选择一个或多个随机条目

$rand_words = array_rand($pieces, 2);

,这样 $rand_words 将从字符串中随机获得两个单词

示例:

$rand_words[0]= "Stack"
$rand_words[1]= "Over"

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"
太阳哥哥 2024-11-26 06:44:37

使用具有随机开始和长度的 substr

$random_string = substr($text, rand(1, mb_strlen($text) - 20), rand(10, 20));

如果需要,调整您的值并添加更多逻辑。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文