PHP会扭曲所有其他单词?

时间:2009-05-13 11:31:43

标签: php explode

  

重复:Explode over every other word

$string = "This is my test case for an example."

如果我根据' '进行爆炸,我会得到一个

Array('This','is','my','test','case','for','an','example.');

我想要的是每隔一个空间爆炸。

我正在寻找以下输出:

Array( 

[0] => Array ( 

[0] => This is
[1] => is my
[2] => my test
[3] => test case 
[4] => case for 
[5] => for example. 

)

所以基本上每两个措辞都会被输出。

任何人都知道解决方案????

6 个答案:

答案 0 :(得分:3)

这将提供您正在寻找的输出

$string = "This is my test case for an example.";
$tmp = explode(' ', $string);
$result = array();
//assuming $string contains more than one word
for ($i = 0; $i < count($tmp) - 1; ++$i) {
    $result[$i] = $tmp[$i].' '.$tmp[$i + 1];
}
print_r($result);

包含在一个函数中:

function splitWords($text, $cnt = 2) 
{
    $words = explode(' ', $text);

    $result = array();

    $icnt = count($words) - ($cnt-1);

    for ($i = 0; $i < $icnt; $i++)
    {
        $str = '';

        for ($o = 0; $o < $cnt; $o++)
        {
            $str .= $words[$i + $o] . ' ';
        }

        array_push($result, trim($str));
    }

    return $result;
}

答案 1 :(得分:2)

另一个使用“追逐指针”的替代方案就是这个片段。

$arr = explode( " ", "This is an example" );
$result = array();

$previous = $arr[0];
array_shift( $arr );
foreach( $arr as $current ) {
    $result[]=$previous." ".$current;
    $previous = $current;
}

echo implode( "\n", $result );

不需要索引和计数总是很有趣,但将所有这些内部代表性内容留给foreach方法(或array_map等)。

答案 2 :(得分:1)

没有循环的简短解决方案(以及可变字数):

    function splitStrByWords($sentence, $wordCount=2) {
        $words = array_chunk(explode(' ', $sentence), $wordCount);
        return array_map('implode', $words, array_fill(0, sizeof($words), ' '));
    }

答案 3 :(得分:0)

我想到了两个快速选项:每个单词都会爆炸并成对重新组合,使用正则表达式来分割字符串而不是爆炸()。

答案 4 :(得分:0)

$arr = explode($string);
$arr2 = array();
for ( $i=0; $i<size($arr)-1; $i+=2 ) {
    $arr2[] = $arr[i].' '.$arr[i+1];
}
if ( size($arr)%2==1 ) {
    $arr2[] = $arr[size($arr)-1];
}

$ arr2是解决方案。

答案 5 :(得分:0)

  $content="This is my test case for an example";
  $tmp=explode(" ",$content);
  $text = array();
  $b=0;
  for ($i = 0; $i < count($tmp)/2; $i++) {
      $text[$i] = $tmp[$b].' '.$tmp[$b + 1];
      $b++;
  $b++;
  }
  print_r($text);