In PHP development, it is often necessary to operate files, including reading, writing and modifying. For modifying specified lines in the file, we can use some common methods to achieve it.
1. Use the file function
The file function is a function commonly used in PHP to read files. It can read the contents of a file and store it into an array. Each array element corresponds to the file. a line in . We can use this feature to modify specific lines in the file.
The specific implementation ideas are as follows:
The following is the implementation code:
function modify_file_line($file_path, $line_number, $new_contents) { // 读取文件内容到数组中 $file_array = file($file_path); // 修改数组中的指定行 $file_array[$line_number - 1] = $new_contents; // 将数组中的内容重新合并成一个字符串 $new_file_content = implode("", $file_array); // 将修改后的字符串写回到文件中 $file_handle = fopen($file_path, "w"); fwrite($file_handle, $new_file_content); fclose($file_handle); return true; }
Used as follows :
modify_file_line('test.txt', 5, 'new contents');
Note: When modifying the file in this method, the entire file will be loaded into the memory. If the file is larger, it will occupy more memory and may cause an out of memory error.
2. Use the fopen and fgets functions
Another way to modify the specified line of the file is to use the fopen and fgets functions. This method only needs to store the contents of the specified line in memory instead of the entire file, so it is more efficient for processing large files.
The specific implementation ideas are as follows:
The following is the implementation code:
function modify_file_line($file_path, $line_number, $new_contents) { // 打开文件并读取指定行的内容 $file_handle = fopen($file_path, "r"); $line_count = 0; $new_file_content = ""; while (!feof($file_handle)) { $line_count++; $line_content = fgets($file_handle); if($line_count == $line_number) { $new_file_content .= $new_contents."\n"; } else { $new_file_content .= $line_content; } } // 关闭文件句柄 fclose($file_handle); // 将新内容写回文件中 $file_handle = fopen($file_path, "w"); fwrite($file_handle, $new_file_content); fclose($file_handle); return true; }
Usage is the same as above:
modify_file_line('test.txt', 5, 'new contents');
Summary:
Both of the above two methods can modify the file. Specify row. The first method is simpler, but may take up more memory for large files. The second method is to read the file content line by line, which is more efficient and suitable for large file processing.
The above is the detailed content of php modify the specified line of the file. For more information, please follow other related articles on the PHP Chinese website!