【问题标题】:How to extract random substrings from a string in php?如何从php中的字符串中提取随机子字符串?
【发布时间】:2011-07-11 04:35:05
【问题描述】:

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

假设我有这个文本

$text = "Some totally random text I have, and I want to work on it! But need some php skillz...";

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

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

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

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

【问题讨论】:

  • 你的意思是你对何时或如何制作子字符串没有任何条件??
  • 感谢您的评论,一个条件是在空白处截断,因此脚本不会在中间截断单词。

标签: php keyword


【解决方案1】:
$words = explode(' ', $string);
$numWords = count($words);
echo join(' ', array_slice($words, mt_rand(0, $numWords - 1), mt_rand(1, $numWords)));

【讨论】:

    【解决方案2】:

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

    $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"
    

    【讨论】:

    • 感谢苏丹塔,我怎样才能将其修改为仅在空白处截断?
    • @giorgio79 - 你能在这里发布一个例子吗?
    • 当然,所以如果我们有这个$text = "Some totally random text I have, and I want to work on it! But need some php skillz..."; 我认为您的解决方案也会像这样提取 sg "ally rand" 但是我希望截止值始终位于空白处,所以它应该是 "totally random"
    • 在这几分钟内检查不出来
    【解决方案3】:

    使用substr 随机开始和长度。

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

    根据需要调整您的价值观并添加更多逻辑。

    【讨论】:

    • 感谢 Blair,我如何将其修改为仅在空白处截断?
    • 这不是 100% 正确如果随机数 > 字符串长度会发生什么?它总是会给出完整的字符串
    • 我知道,我没有时间写一个完整的例子,这就是为什么我有最后一行文字。无论如何,deceze 有更好的方法。
    猜你喜欢
    • 2011-11-17
    • 1970-01-01
    • 2017-04-01
    • 1970-01-01
    • 2011-07-21
    • 1970-01-01
    • 2012-10-24
    相关资源
    最近更新 更多