applelover Posted May 25, 2008 Share Posted May 25, 2008 I have a string that I wish to divide into 100 words per part so that each part can be displayed on the page separately. ie. $text = "The quick brown fox jumps over the lazy dog (x 100 times)" How do I split this text into an array 100 words at a time? Thanks. Link to comment https://forums.phpfreaks.com/topic/107233-array-quesition/ Share on other sites More sharing options...
pocobueno1388 Posted May 25, 2008 Share Posted May 25, 2008 Try <?php $text = "The quick brown fox jumps over the lazy dog The quick brown fox jumps over the lazy dog The quick brown fox jumps over the lazy dog"; $text = explode(" ", $text); //array to hold the sections of words in $words = array(); //var to hold the sets in $set = ""; $count = 1; foreach ($text as $word){ $set .= $word . ' '; if ($count == 100){ $words[] = $set; $set = ""; $count = 0; } $count++; } echo '<pre>',print_r($words),'</pre>'; ?> Link to comment https://forums.phpfreaks.com/topic/107233-array-quesition/#findComment-549789 Share on other sites More sharing options...
sasa Posted May 25, 2008 Share Posted May 25, 2008 or <?php $a = "The quick brown fox jumps over the lazy dog. "; $a = str_repeat($a, 50); $a = explode(' ', $a); $a = array_chunk($a, 100); foreach ($a as $c) $out[] = implode(' ', $c); print_r($out); ?> Link to comment https://forums.phpfreaks.com/topic/107233-array-quesition/#findComment-549795 Share on other sites More sharing options...
pocobueno1388 Posted May 25, 2008 Share Posted May 25, 2008 or <?php $a = "The quick brown fox jumps over the lazy dog. "; $a = str_repeat($a, 50); $a = explode(' ', $a); $a = array_chunk($a, 100); foreach ($a as $c) $out[] = implode(' ', $c); print_r($out); ?> That pretty much put my code to shame...much more efficient. Link to comment https://forums.phpfreaks.com/topic/107233-array-quesition/#findComment-549798 Share on other sites More sharing options...
applelover Posted May 26, 2008 Author Share Posted May 26, 2008 No thank you poco for posting a solution so fast! Actually I can follow your code more easily as I'm not familiar with php functions. And thanks to Sasa as well for posting another solution, so advanced :-) Both code works and did what I wanted to do. Link to comment https://forums.phpfreaks.com/topic/107233-array-quesition/#findComment-549862 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.