How can file_get_contents() and str_replace() be used to delete a specific line from a text file in PHP?
To delete a specific line from a text file in PHP, you can use file_get_contents() to read the contents of the file into a string, then use str_replace() to remove the specific line from the string. Finally, you can write the modified string back to the file using file_put_contents().
<?php
// File path
$file = 'example.txt';
// Read the file contents into a string
$content = file_get_contents($file);
// Line to delete
$lineToDelete = "This is the line to delete";
// Remove the specific line from the string
$content = str_replace($lineToDelete, '', $content);
// Write the modified string back to the file
file_put_contents($file, $content);
?>
Keywords
Related Questions
- How does the interaction between HTML, CSS, and JavaScript play a role in resolving display issues with PHP-generated content?
- What are the benefits of using a Mailer class in PHP for sending emails instead of the mail() function?
- What are some best practices for efficiently handling database queries and updates in PHP scripts like the one provided in the forum thread?