Jump to content

array quesition


applelover

Recommended Posts

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
Share on other sites

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
Share on other sites

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
Share on other sites

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
Share on other sites

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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.