php - 用2个单词得到2个单词

时间:2012-02-17 21:44:09

标签: php

我希望代码在php中获得2个单词的2个单词 例如:

stackoverflow the best site of asking

结果:

2 words : stackoverflow the
2 words : best site
2 words : of asking

2 个答案:

答案 0 :(得分:5)

$array_of_words = implode(' ',array_chunk(explode(' ',$text), 2));
print_r($array_of_words);

这应该给你

  

0 => stackoverflow 1 =>最佳网站2 =>询问

  • array_chunk()

      

    将数组块化为大块大块。最后一个块可能包含少于大小的元素

  • implode()

      

    使用胶水串

    连接数组元素

答案 1 :(得分:1)

@ MyStream的答案很好,但另一种选择是:

$str = 'stackoverflow the best site of asking';
preg_match_all('#\S+(\s+\S+)?#', $str, $matches);
var_dump($matches[0]);

输出:

array(3) {
  [0]=>
  string(17) "stackoverflow the"
  [1]=>
  string(9) "best site"
  [2]=>
  string(9) "of asking"
}