Format text file, replace few whitespaces with commas.

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • kris06
    New Member
    • Mar 2008
    • 2

    Format text file, replace few whitespaces with commas.

    Hi All,

    I have a textfile and i need to format it, so that i can import it to the mysql database.

    The textfile contains 9 colums of data separated by a space. I want to replace only the first 8 whitespaces separating those 9 colums, because the 9th column contains a sentence separated by space. similaryly i want all the rows in that file to get updated in the same fashion.

    Heres how the contents of the textfile looks:
    -------------------------------------------


    2223 A None NULL 5 03/05/2008 mike Not_Apply active directory feature
    3232 O 4.5.4 39 7 04/05/2008 tim cisco bitrate enhancement

    similaryly many more rows.

    Only the first 8 columns needs to be delimited with a comma. I been stuck with this for many hours now. any help would be appreciated.


    /Kris
  • ronverdonk
    Recognized Expert Specialist
    • Jul 2006
    • 4259

    #2
    When you are sure about the correct format of your text file you can[php]
    $text=str_repla ce(' ', ' ', $text); // replace all double blanks by one blank
    $text=str_repla ce(' ', ',', $text,8); // replace first 8 blanks with comma[/php]Ronald

    Comment

    • kris06
      New Member
      • Mar 2008
      • 2

      #3
      Originally posted by ronverdonk
      When you are sure about the correct format of your text file you can[php]
      $text=str_repla ce(' ', ' ', $text); // replace all double blanks by one blank
      $text=str_repla ce(' ', ',', $text,8); // replace first 8 blanks with comma[/php]Ronald
      But i think i need to read from the start of the file to the end, and make changes line by line. i am not sure, how to accomplish that !. please help.

      Comment

      • ronverdonk
        Recognized Expert Specialist
        • Jul 2006
        • 4259

        #4
        You mean you don't know how to read a fiole line by line? Allright then[php]<?php
        $file = "test.txt";
        $handle = fopen($file,"r" );
        if ($handle) {
        while(!feof($ha ndle)){
        $text = fgets($handle, 4096); // read one line
        $text=str_repla ce(' ', ' ', $text); // replace double blanks by 1 blank
        $text=str_repla ce(' ', ',', $text,8); // replace first 8 blanks with comma

        }
        }
        ?>[/php]Ronald

        Comment

        Working...