Home > Article > Backend Development > How to modify a line of content in a file in php
php method to modify the content of a line in a file: 1. Create a php sample file; 2. Use the "file()" function to open all lines of the specified file, find the line to be modified, and modify the content of the line; 3. Use the "file_put_contents()" function to put the modified content back into the file.
Operating system for this tutorial: Windows 10 system, php8.1.3 version, Dell G3 computer.
Modifying the implementation of a one-line function requires the following steps:
1. Use PHP's file operation function to open the specified file.
2. Read the file content and store the content of each line in the memory in an array.
3. Find the number of lines to be modified and modify the content of the line.
4. Write the modified content back to the file.
The sample code is as follows:
function modifyLine($filename, $lineNumber, $newContent) { // 打开文件,读取所有行 $lines = file($filename); // 修改指定行的内容 $lines[$lineNumber - 1] = $newContent . ""; // 把内容写回文件 file_put_contents($filename, implode("", $lines)); }
In the modified code, the file()
function reads all lines of the specified file and stores the content of each line in an array element. Then, based on the line number passed in, we find the line to be modified in the array and modify it to new content.
Finally, we use the file_put_contents()
function to put the modified content back into the file.
The above is the detailed content of How to modify a line of content in a file in php. For more information, please follow other related articles on the PHP Chinese website!