简体   繁体   English

PHP脚本修改文件中位置的文本

[英]PHP script to modify text at position in file

How do I go about writing a php script that subtracts 10 from a 6 digit number at a specific location in a text file. 我该如何编写一个php脚本,该脚本在文本文件中的特定位置从6位数字中减去10。 For example, I have "030.00" at position 105-110 in a file and I want to subtract 010 to make it "020.00" 例如,我在文件中位置105-110处有“ 030.00”,我想减去010使其成为“ 020.00”

$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(). 使用fopen()打开文件。 Do a foreach loop to loop through each line. 做一个foreach循环遍历每一行。

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. 然后在有问题的行上使用substr()来获取所需的数据,然后将数据作为字符串。 Convert it to an int and you can subtract from it. 将其转换为int,然后可以减去。

Hope that helps! 希望有帮助!

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. 但是你得到了理想。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM