【问题标题】:Get a certain number of random words from a string从字符串中获取一定数量的随机单词
【发布时间】:2011-09-11 19:25:04
【问题描述】:

喜欢:

The quick, brown fox jumps over a lazy dog. DJs flock by when MTV ax quiz prog. Junk MTV quiz graced by fox whelps. Bawds jog, flick quartz, vex nymphs. Waltz, bad nymph, for quick jigs vex! Fox nymphs grab quick-jived waltz. Brick quiz whangs jumpy veldt fox. Bright vixens jump; dozy fowl quack. Quick wafting zephyrs vex bold Jim. Quick zephyrs blow, vexing daft Jim.

(这只是示例文本,真实的要长得多)

我怎样才能从这段文字中说出 5 个单词?

我尝试使用 explode(' ', $text); 然后随机排列数组并从中挑选 5 个元素,但我得到了所有标点符号和其他字符。我只想要 a-z 字符。此外,单词需要至少有 3 个字符

【问题讨论】:

    标签: php arrays string


    【解决方案1】:

    您可以为此使用内置的str_word_count

    $words = str_word_count($str, 1);
    shuffle($words);
    $selection = array_slice($words, 0, 5);
    

    See it in action.

    如果您担心性能,您还可以使用另一种方式(例如array_rand)从$words 数组中挑选随机单词;这是最方便的。

    【讨论】:

      【解决方案2】:

      使用preg_split:

      $words = preg_split('#[^a-z0-9]+#', $string, -1, PREG_SPLIT_NO_EMPTY);
      $key = array_rand($words);
      return $words[$key];
      

      这会将字符串拆分为任何非字母数字字符序列。

      如果您处理的是 utf-8 数据,请尝试以下方法:

      $words = preg_split('#[^\pL\pN]+#u', $string, -1, PREG_SPLIT_NO_EMPTY);
      

      【讨论】:

        【解决方案3】:

        只需删除不需要的字符

        $words = explode(' ', $string);
        $words = array_map (function ($word) {
            trim($word, '.,-:;"\'');
        }, $words);
        

        按字长过滤

        $words = array_filter($words, function($word) {
            return strlen($word) > 2;
        }, $words);
        

        【讨论】:

        • 我会保留想要的字符,而不是;)
        【解决方案4】:

        $string = preg_replace("/[^a-z ]+/i", "", $string);

        在你做爆炸之前

        【讨论】:

        • 这不起作用,因为它会删除空格,然后explode 将不再起作用。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-24
        • 2017-03-17
        • 2022-11-23
        • 1970-01-01
        • 2011-02-18
        相关资源
        最近更新 更多