Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/37.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 从字符串中获取一定数量的随机单词_Php_Arrays_String - Fatal编程技术网

Php 从字符串中获取一定数量的随机单词

Php 从字符串中获取一定数量的随机单词,php,arrays,string,Php,Arrays,String,比如: (这只是示例文本,实际文本要长得多) 我怎样才能从这篇课文中得到5个单词呢 我试着使用explode(“”,$text)然后洗牌数组并从中选择5个元素,但我得到所有标点和其他字符。我只想要a-z字符。此外,单词至少需要有3个字符使用: $words = preg_split('#[^\pL\pN]+#u', $string, -1, PREG_SPLIT_NO_EMPTY); 这将拆分任何非字母数字字符序列上的字符串 如果使用utf-8数据,请尝试以下方法: $words = preg

比如:

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

我怎样才能从这篇课文中得到5个单词呢

我试着使用
explode(“”,$text)
然后洗牌数组并从中选择5个元素,但我得到所有标点和其他字符。我只想要a-z字符。此外,单词至少需要有3个字符使用:

$words = preg_split('#[^\pL\pN]+#u', $string, -1, PREG_SPLIT_NO_EMPTY);
这将拆分任何非字母数字字符序列上的字符串

如果使用utf-8数据,请尝试以下方法:

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

只需删除不需要的字符

$words = preg_split('#[^\pL\pN]+#u', $string, -1, PREG_SPLIT_NO_EMPTY);
并按字长过滤

$words = explode(' ', $string);
$words = array_map (function ($word) {
    trim($word, '.,-:;"\'');
}, $words);
$string=preg_replace(“/[^a-z]+//i”,”,$string)

在进行分解之前,可以使用内置的:

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


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

我会保留想要的字符;)这将不起作用,因为它将删除空格,然后
分解
将不再起作用。
$words = str_word_count($str, 1);
shuffle($words);
$selection = array_slice($words, 0, 5);