PHP explode over every other word with a twist?

心不动则不痛 提交于 2019-12-08 03:29:58

问题


Duplicate: Explode over every other word

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

If I do explode based on ' ' I get an

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

What I want is an explode for every other space.

I'm looking for the following output:

Array( 

[0] => Array ( 

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

)

so basically every 2 worded phrases is outputted.

Anyone know a solution????


回答1:


this will provide the output you're looking for

$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);

Wrapped in a function:

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;
}



回答2:


An alternative, making use of 'chasing pointers', would be this snippet.

$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 );

It's always fun to not need indices and counts but leave all these internal representational stuff to the foreach method (or array_map, or the like).




回答3:


A short solution without loops (and a variable word count):

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



回答4:


Two quick options come to mind: explode by every word and reassemble in pairs, use a regular expression to split the string instead of explode().




回答5:


$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 is the solution.




回答6:


  $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);


来源:https://stackoverflow.com/questions/857441/php-explode-over-every-other-word-with-a-twist

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!