ionfish
ionfish

Reputation: 171

Explode a string into into 3 or 4-word strings

$str =  "Hello fri3nd, you're looking good today!  What a Great day this is!  How     fancy and cool!";
$pieces = explode(" ",$str, 3);

print_r($pieces);

This gives me:

$pieces[0] = 'Hello';
$pieces[1] = 'fri3nd,';
$pieces[2] = 'you\'re looking good today!  What a Great day this is!  How     fancy and cool!';

How can I explode into every 3 or 4 words?

Upvotes: 1

Views: 282

Answers (3)

mickmackusa
mickmackusa

Reputation: 47992

Make 3 or 4 repetitions of a regex pattern that matches one or more visible characters followed by one or more whitespace characters.

This will produce strings of three/four words, with the exception of the last element which may have less than three/four words depending on the total word count.

Code: (Demo)

$str = "Hello fri3nd, you're looking good today!  What a Great day this is!  How     fancy and cool!";

var_export(
    preg_split('/(?:\S+\K +){3}/', $str)
);

This is an adjustment of this answer which doesn't need to accommodate multiple spaces.

Upvotes: 1

Yoshi
Yoshi

Reputation: 54649

Maybe:?

<?php
$str =  "Hello fri3nd, you're looking good today!  What a Great day this is!  How     fancy and cool!";

$array = array_map(create_function('$a', 'return implode(" ", $a);'), array_chunk(preg_split('/\s+/', $str), 3));
var_dump($array);

Explanation:

  • first you split the string at any (combined) whitespace: preg_split
  • then 'split' the resulting array: array_chunk
  • you then apply implode using array_map on any resulting group of words

Upvotes: 2

Celmaun
Celmaun

Reputation: 24762

Use the php str_split function:-

$pieces = str_split( $str, 3);

Upvotes: 0

Related Questions