Home > Backend Development > PHP Tutorial > How Can I Delete a Specific Line from a File Using PHP?

How Can I Delete a Specific Line from a File Using PHP?

Patricia Arquette
Release: 2024-12-13 18:51:10
Original
332 people have browsed it

How Can I Delete a Specific Line from a File Using PHP?

Eliminating Lines from Files Using PHP

To erase a complete line from a file in PHP, where the line number is unknown, consider the following steps:

  1. Obtain File Contents: Utilize the file_get_contents() function to retrieve the entire contents of the file into a string variable.
  2. Perform String Manipulation: Employ the str_replace() function to substitute the specific line with an empty string.
  3. Save Updated Contents: Finally, use the file_put_contents() function to overwrite the file with the modified contents.

Example Code:

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

This solution effectively removes the specified line from the file without necessitating the knowledge of its line number.

The above is the detailed content of How Can I Delete a Specific Line from a File Using 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