We help IT Professionals succeed at work.
Get Started

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

TonyHull
TonyHull asked
on
274 Views
Last Modified: 2012-05-05
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;
       }
Comment
Watch Question
Commented:
This problem has been solved!
Unlock 1 Answer and 2 Comments.
See Answer
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE