获得一定数量的随机字从字符串 [英] Get a certain number of random words from a string
问题描述
我爱:
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.
(这只是示例文本,真正的是更长的时间)
(this is just sample text, the real one is much longer)
我怎样才能让我们说5个字从这段文字?
How can I get let's say 5 words from this text?
我试着用爆炸('',$文本);
然后洗牌数组,并从中挑选5个元素,但我得到的所有的标点和其他字符。我只想要一个-Z字符。还词语需要有至少3个字符
I tried using explode(' ', $text);
Then shuffle the array and pick 5 elements from it, but I get all the punctuation and other characters. I just want a-z characters. Also the words need to have at least 3 characters
推荐答案
您可以使用内置的 str_word_count
此:
You can use the built-in str_word_count
for this:
$words = str_word_count($str, 1);
shuffle($words);
$selection = array_slice($words, 0, 5);
See it in action.
您也可以用另一种方式(如 array_rand从
)数组,如果您关心的性能;这仅仅是最方便的。 $词挑选出随机的话
You can also use another way (such as array_rand
) of picking out random words from the $words
array if you are concerned about performance; this is just the most convenient.
这篇关于获得一定数量的随机字从字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!