Reputation: 171
$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
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
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:
preg_split
array_chunk
implode
using array_map
on any resulting group of wordsUpvotes: 2