php 读写文件不保存前导空格

php read write file not saving leading whitespace

我正在处理一个大约 2000 行长的文件。这是一个简单的读取、替换文本并回写,但是不会保留前导空格。

有什么想法吗?

    <?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

如果你想要白色 space 修改下面的行

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

进入

$line = fgets($access);

这应该可以解决您的问题。