I have sentence like this:
I am in love with you
I want this to be in following combination for 3 words from left to right.
I am in
am in love
in love with
love with you
I tried the code below, but I think I'm complicating it...
$data = array_chunk(explode(" ", $sarr), 3);
$data = array_map(function($value) {
return sprintf("<span>%s</span>", implode(" ", $value));
}, $data);
echo implode("
", $data);
Any ideas on how to do it fast and efficiently? This must work for 5000 words.
You could use Regular Expressions to work around this. You match one word then capture two other following words with a positive lookahead and stick them together within a foreach
loop.
$words = [];
preg_match_all('~\b\w+(?=((?:\s+\w+){2}))~', $str, $matches);
foreach ($matches[0] as $key => $word) {
// 1st iteration => $word = "I", $matches[1][0] = " am in"
$words[] = $word . $matches[1][$key];
}
Outputs (print_r($words);
):
Array
(
[0] => I am in
[1] => am in love
[2] => in love with
[3] => love with you
)
Output of echo implode(PHP_EOL, $words);
:
I am in
am in love
in love with
love with you
You were certainly off to a strong start, but you want a rolling window over your array. You can achieve this like so:
// split the string into words
$words = explode(" ", $sarr);
// for each index in the array, get that word and the two after it
$chunks = array_map(function($i) use ($words) {
return implode(" ", array_slice($words,$i,3));
}, array_keys($words));
// cut off the last two (incomplete) chunks
$chunks = array_slice($chunks,0,-2);
// glue the result together
echo implode("
",$chunks);