How do I go about 开发者_Go百科writing a php script that subtracts 10 from a 6 digit number at a specific location in a text file. For example, I have "030.00" at position 105-110 in a file and I want to subtract 010 to make it "020.00"
Being a standard format, I would recommend something like this:
$myFile = "yourFile.txt";
$fh = fopen($myFile, 'r');
$fileContent = fread($fh, filesize($myFile));
$toBeReplaced = (float) substr($fileContents, 105, 6);
$newString = str_pad( ($toBeReplaced - 10), 6, "0", STR_PAD_LEFT );
$finalString = substr($fileContents, 0, 104) . $newString . substr($fileContents, 111, strlen ($fileContents) - 117);
fclose($fh);
$myFile = "newFile.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
fwrite($fh, $finalString);
fclose($fh);
I hope I have calculated correct positions, as I cannot test it. But you get the ideea.
$val = (float) substr($str, 105, 5);
$val = number_format($val - 10, 2);
$str = substr_replace($str, $val, 105, 5);
This should do what you are looking for. The other choice would be a regex, but there could be room for error. If you know the exact position each time you could do it this way.
--edited--
fixed the position on the substr
Open the file with fopen(). Do a foreach loop to loop through each line.
foreach ($lines as $line_num => $line) {
Then use substr() on the line in question to get the data you want and you'll have the data as a string. Convert it to an int and you can subtract from it.
Hope that helps!
精彩评论