Link to home
Start Free TrialLog in
Avatar of TonyHull
TonyHull

asked on

read and break file into words, divide by certain number and output to new files

Hi
I am trying to import a text file and export it into smaller files. For example, I have a txt file with 88 words, I want it to be broken down into 5 files. It does work but it keeps adding the previous words to each consequtive file.
So if file 1.txt has 18 words, file 2.txt should have words 19 to 36, file 3.txt 37 to 54. Instead it adds file 2 to file one then file three to 2 and 1.
Can anyone fix this or write it more elegantly??

$numWords = 88;
$count = 5;

$k = 0;
      $increment = $numWords;
      $j_increment = 0;
       while($k < $count) {
              for($j=$j_increment ; $j < $increment; $j++)
                    {
         if (eregi("[0-9A-Za-zÀ-ÖØ-öø-ÿ]", $arrayNew[$j]))
                    $newFile.=$arrayNew[$j] . ' ';
                 }
             $newFileNum = $fileAddress.(($k + 1) . '.txt');
             if (!$fh = fopen($newFileNum,"a")) { echo "Cannot open file"; }  
            if (!fwrite($fh, $newFile)) { echo "Cannot write to file"; }  
            echo "You have successfully written data to $newFileNum";  
            fclose($fh);
       $k++;
       $increment += $numWords;
       $j_increment += $numWords;
       }
ASKER CERTIFIED SOLUTION
Avatar of elfe69
elfe69
Flag of Switzerland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of TonyHull
TonyHull

ASKER

Yep that did the trick. Many thanks