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

时间:2015-01-09 17:23:49

标签: php regex

假设

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

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

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

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

2 个答案:

答案 0 :(得分:5)

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

\b\w{4}\b

RegEx Demo

<强>代码:

$re = '/\b\w{4}\b/'; 
$str = "There are so many words in a para"; 

preg_match_all($re, $str, $m);

print_r($m[0]);

答案 1 :(得分: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);