Skip to content

Instantly share code, notes, and snippets.

@six519
Created September 5, 2012 09:27
Show Gist options
  • Save six519/3634045 to your computer and use it in GitHub Desktop.
Save six519/3634045 to your computer and use it in GitHub Desktop.
Split Words
<?php
function splitWords($paragraph, $numberOfWords) {
$returnArray = array();
$splittedString = explode(" ", $paragraph);
$counter = 0;
$counter2 = 0;
for($x = 0; $x < count($splittedString); $x++) {
$counter += 1;
$returnArray[$counter2] .= $splittedString[$x] . " ";
if($counter == $numberOfWords) {
$counter = 0;
$counter2 += 1;
}
}
return $returnArray;
}
//TESTING
$str = "Japan is an archipelago of 6,852 islands. The four largest islands are Honshū, Hokkaidō, Kyūshū and Shikoku, together comprising about ninety-seven percent of Japan's land area. Japan has the world's tenth-largest population, with over 127 million people. Honshū's Greater Tokyo Area, which includes the de facto capital city of Tokyo and several surrounding prefectures, is the largest metropolitan area in the world, with over 30 million residents.";
var_dump(splitWords($str,5));
/** OUTPUT
array(14) {
[0]=>
string(27) "Japan is an archipelago of "
[1]=>
string(32) "6,852 islands. The four largest "
[2]=>
string(41) "islands are Honshū, Hokkaidō, Kyūshū "
[3]=>
string(39) "and Shikoku, together comprising about "
[4]=>
string(37) "ninety-seven percent of Japan's land "
[5]=>
string(28) "area. Japan has the world's "
[6]=>
string(40) "tenth-largest population, with over 127 "
[7]=>
string(40) "million people. Honshū's Greater Tokyo "
[8]=>
string(28) "Area, which includes the de "
[9]=>
string(28) "facto capital city of Tokyo "
[10]=>
string(40) "and several surrounding prefectures, is "
[11]=>
string(33) "the largest metropolitan area in "
[12]=>
string(24) "the world, with over 30 "
[13]=>
string(19) "million residents. "
}
**/
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment