0

I have a question. I have a text file that I have installed in PHP, I want to separate 350 words and save them to text files like 1.txt 2.txt 3.txt ... How can I do this?

I tried this but it didn't work:

$text = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam
 nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.
Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et.";

$word = explode(" ", $text);
$count = count($word);
$limit = 40;
if($count <= $limit) { 
  $cut = $count * 50 / 100; 
} else { 
  $cut = $limit; 
}
for($i = 0; $i <= $cut; $i++) { 
  $text1= $word[$i] . ' '; 
  echo $text1;
}
double-beep
  • 5,031
  • 17
  • 33
  • 41
nymfer
  • 21
  • 5

2 Answers2

0

There are other forms of this question already answered take a look here PHP script to split large text file into multiple files.

Most people split at certain interval of lines because it is easy to control with a loop.

Cut the content after 10 words

Or cut your string after 350 words just make sure that your reg expression accounts for whitespace and special characters other than letters such as a comma or quote.

Orlando P.
  • 621
  • 3
  • 19
0

Here is my solution. Not a lot of code. This will return arrays with x words each, or for last result, the remaining words if less than x.

$text = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam  nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et.";

$chunkSize = 5;
print_r(array_chunk(str_word_count($text, 1), $chunkSize));
Array (
    [0] => Array
    (
        [0] => Lorem
        [1] => ipsum
        [2] => dolor
        [3] => sit
        [4] => amet
    )

    [1] => Array
    (
        [0] => consectetuer
        [1] => adipiscing
        [2] => elit
        [3] => sed
        [4] => diam
    )
...

PHP has a function for everything (cough @Erik). See str_word_count and array_chunk.

ficuscr
  • 6,975
  • 2
  • 32
  • 52