php:如何从句子中获取n个长度的单词


php: How to get n length words from sentence?

>假设

$length = 4;
$sentence = 'There are so many words in a para';

由于给定长度为 4,因此输出将为:-

$output = array('many', 'para');

获得预期输出的正则表达式是什么?

您可以使用此正则表达式:

'b'w{4}'b

正则表达式演示

法典:

$re = '/'b'w{4}'b/'; 
$str = "There are so many words in a para"; 
preg_match_all($re, $str, $m);
print_r($m[0]);

只是为了好玩,并展示实现相同目标的非正则表达式方式:

$length = 4;
$sentence = 'There are so many words in a para';
$i = 0;
$words = array_filter(
    str_word_count($sentence, 1),
    function ($word) use(&$i, $length) {
        return ++$i % $length == 0;
    }
);
var_dump($words);