Home > Backend Development > PHP Tutorial > How to Efficiently Delete a Specific Line from a File in PHP?

How to Efficiently Delete a Specific Line from a File in PHP?

Barbara Streisand
Release: 2024-12-06 19:59:16
Original
1039 people have browsed it

How to Efficiently Delete a Specific Line from a File in PHP?

Deleting Lines from a File Using PHP

Removing specific lines from a text file can be a common task in PHP development. Suppose you have a file named $dir and a $line variable representing a complete line in the file. However, you don't know its line number. To delete this line, you can use the following steps:

1. Read the Contents of the File:

$contents = file_get_contents($dir);
Copy after login

2. Perform String Manipulation to Remove the Line:

str_replace can substitute occurrences of $line with an empty string:

$contents = str_replace($line, '', $contents);
Copy after login

3. Update the File with the Modified Contents:

file_put_contents($dir, $contents);
Copy after login

This code replaces the $line with an empty string, effectively erasing the line from the file. Note that file_put_contents will overwrite the existing file contents, so make sure you have any necessary backups in place.

awk Method:

While the above method is simple and straightforward, you can also use awk to delete the line:

awk -F'\r' '!/^$line$/' $dir > /tmp/file.txt
Copy after login
  • -F'r': Specifies line termination as carriage return (r).
  • !/^$line$/: Inverts grep logic to print all lines except the specified one.
  • /tmp/file.txt: Write the output to a temporary file.

Once you have the updated file, you can replace the original with the temporary one:

mv /tmp/file.txt $dir
Copy after login

This method is particularly useful when dealing with large files where line numbers are unknown.

The above is the detailed content of How to Efficiently Delete a Specific Line from a File in PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template