Home > OS >  How can I split string every three words - php [duplicate]
How can I split string every three words - php [duplicate]

Time:09-16

I need to split a string in every three words using php

"This is an example of what I need."

The output would be:

is an example
an example of
example of what
of what I
what I need

i have this example with java

String myString = "This is an example of what I need.";
        String[] words = myString.split("\\s ");
        for (int i = 0; i < words.length; i  ) {
            String threeWords;
              if (i == words.length - 1)
                  threeWords = words[i]; 
              else if(i == words.length - 2)
                  threeWords = words[i]   " "   words[i   1]; 
              else 
                  threeWords = words[i]   " "   words[i   1]   " "   words[i   2];
              System.out.println(threeWords);
    }

Thanks for the help!

CodePudding user response:

Solution that use explode, array_slice and implode.

$example = 'This is an example of what I need.';

$arr = explode(" ",$example);
foreach($arr as $key => $word){
  $subArr = array_slice($arr,$key,3);
  if(count($subArr) < 3) break;
  echo implode(" ",$subArr)."<br>\n";
}

Output:

This is an
is an example
an example of
example of what
of what I
what I need.

CodePudding user response:

Your request is ambiguous at first glance, so I have followed your example output.

Here is one way and btw hi. See output.

$example = 'This is an example of what I need.';


$store = [];
$strings = [];
$token = strtok($example, " ");
$i = 0;
while ($token !== false){
    if($i < 3){
       $store[] = ' '.$token;
    }
    else{
      array_shift($store);
      $store[] = ' '.$token;
    }
    if($i > 1){
      $strings[] = implode($store);
    }
  $i  ;
  $token = strtok(" ");
}




print_r($strings);

Output
(
    [0] =>  This is an
    [1] =>  is an example
    [2] =>  an example of
    [3] =>  example of what
    [4] =>  of what I
    [5] =>  what I need.
)

  • Related