Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

explode text but returning each array piece as three words

Tags:

php

I'm getting troubles on a simple php function! What i want to do is:

$text = "this is my data content with many words on it";

I want to write a function that turns the variable string $text as an array like this:

$array = array("this is my", "data content with", "many words on", "it");

In other words, each array piece should have 3 words on it!

like image 682
Mbarry Avatar asked May 03 '26 05:05

Mbarry


1 Answers

This should work:

function split3($text)
{
    $array = array();
    foreach(explode(' ',$text) as $i=>$word)
    {
        if($i%3) {
            $array[floor($i/3)] .= ' '.$word;
        } else {
            $array[$i/3] = $word;
        }
    }
    return $array;
}

$text = "this is my data content with many words on it";
var_dump(split3($text));

returns:

array(4) {
  [0]=>
  string(10) "this is my"
  [1]=>
  string(17) "data content with"
  [2]=>
  string(13) "many words on"
  [3]=>
  string(2) "it"
}
like image 121
lheurt Avatar answered May 05 '26 19:05

lheurt