How can one search for a specific string in a text file and delete all lines below it in PHP?
To search for a specific string in a text file and delete all lines below it in PHP, you can read the file line by line, check if the specific string is found, and then write only the lines above it to a new file. Once the specific string is found, you can stop writing lines to the new file.
$specificString = "example"; // specify the string to search for
$filename = "input.txt"; // specify the input file
$outputFilename = "output.txt"; // specify the output file
$found = false;
$lines = file($filename);
$output = fopen($outputFilename, "w");
foreach ($lines as $line) {
if (strpos($line, $specificString) !== false) {
$found = true;
}
if (!$found) {
fwrite($output, $line);
}
}
fclose($output);
Keywords
Related Questions
- What are the potential security risks of using HTML form-based authentication for password-protected video streaming in PHP?
- In the provided code, what best practice should be implemented to prevent XSS attacks in form inputs?
- What potential issues can arise when using the date() and mktime() functions in PHP, particularly when dealing with dates before 1970?