开发者

php, file character

开发者 https://www.devze.com 2023-03-20 14:25 出处:网络
Is there wa开发者_Python百科y to replace last charcter in each line within file using php? I have file that has bunch of lines and at the end of each line there is a character that I need to remove.

Is there wa开发者_Python百科y to replace last charcter in each line within file using php?

I have file that has bunch of lines and at the end of each line there is a character that I need to remove.

Do I have to read file line by line or is there magic that I can use to strip last character in each line of a file?

How would I do that?

Any help is appreciated.


You are going to have to read in each line and edit each line with. What OS are you using? Unix has some useful tools (awk, sed) for this type of problem.


Is the character the same character every time? You can load your file into a string using

$mystr = file_get_contents("myfile.txt");

and then use preg_replace to remove your character from the string.

$mystr = preg_replace("yourcharhere","",$mystr);

and then put your string back into the file

$fh = fopen("myfile.txt", 'w');
fwrite($fh, $stringData);
fclose($fh);

You can also add yourcharacterhere+newline in the preg_replace and then cahnge the "" to a newline. That will make it so it only removes your character before a newline. If you have different characters you need to remove, you can use a regular expression and a wildcard to remove any character before a newline.


You would either have to read the file line by line, or load the entire file and then explode it by a linebreak and then loop through that (essentially the same).

0

精彩评论

暂无评论...
验证码 换一张
取 消