Search code examples
phpfilefwritefgetsfputcsv

php read write file not saving leading whitespace


I have a file about 2000 lines long that I am processing. It's a simple read, replace text and write back however, the leading whitespace is not being preserved.

Any ideas?

    <?php
    $access = fopen("oldfile.txt", "r");
    $y=9999;
    for ($i=1; $i<=$y; $i++)
        {
        $line = trim(fgets($access));
        $loc = strpos($line, "findtext", 0);
        if ($loc)
            {
            $loc = $loc +6;
            $end =  strpos($line, "endtext", 0);
            $pull = substr($line, $loc, ($end-$loc));

            $loc = strpos($line, 'foundthis', 0);
            $end = $loc +12;

            $newline = substr($line, 0, $loc).'foundthis'.$pull.'" '.
     substr($line, $end);

            }
        else
            { $newline = $line;  }

        file_put_contents("newfile.txt", $newline."\r\n", FILE_APPEND);

        }
    fclose($access);

 ?>

oldfile.txt
    labelinput  "Adhesives" name="MyName"Adhesiveslabel
    labelinput  "Cord, Yarn & Material" name="MyName"Cord, Yarn & 
        labelinput  "Corners" name="MyName"Cornerslabel
            labelinput  "Ink & Ink Pads" name="MyName"Ink & Ink Padslabel

newfile.txt
labelinput  "Adhesives" name="MyName"Adhesiveslabel
labelinput  "Cord, Yarn & Material" name="MyName"Cord, Yarn & Materiallabel
labelinput  "Corners" name="MyName"Cornerslabel
labelinput  "Ink & Ink Pads" name="MyName"Ink & Ink Padslabel

Solution

  • If you want the white space as it is modify below line

    $line = trim(fgets($access));
    

    into

    $line = fgets($access);
    

    This should solve your issue.