PHP explode over every other word with a twist?

独自空忆成欢 提交于 2019-12-08 03:45:27
Sylvain

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

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).

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), ' '));
    }

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().

$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.

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