How can the use of array_slice() in PHP help in extracting specific lines from a text file based on a keyword?
When extracting specific lines from a text file based on a keyword, you can use the `file()` function in PHP to read the file into an array, and then use `array_slice()` to extract the lines that contain the keyword. This function allows you to specify the starting index and length of the slice, making it easy to extract the desired lines.
// Read the text file into an array
$lines = file('example.txt');
// Define the keyword to search for
$keyword = 'specific_keyword';
// Find the index of lines that contain the keyword
$keywordLines = array_keys(array_filter($lines, function($line) use ($keyword) {
return strpos($line, $keyword) !== false;
}));
// Extract the lines that contain the keyword
$extractedLines = array_slice($lines, $keywordLines[0], count($keywordLines));
// Output the extracted lines
foreach ($extractedLines as $line) {
echo $line;
}