Home > Mobile >  How can I split a string into three word chunks?
How can I split a string into three word chunks?

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:

This is an
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);
    }

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){
  //if($key == 0) continue;
  $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.

If you want to suppress the first output with This, remove the comment in the line

//if($key == 0) continue;

If the example can have less than 3 words and these should be output then the line with the break must be as follows:

if(count($subArr) < 3 AND $key != 0) break;

CodePudding user response:

To include only words (notice the fullstop is removed from the last trigram), use str_word_count() to form the array of strings.

Then you need to loop while there are three elements to print.

Code: (Demo)

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

$words = str_word_count($example, 1);
for ($x = 0; isset($words[$x   2]);   $x) {
    printf("%s %s %s\n", $words[$x], $words[$x   1], $words[$x   2]);
}

Output:

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

If you don't like printf(), you could echo implode(' ', [the three elements]).

  • Related