I have a TXT file with 8000 lines. I need to find the first 20 lines that contain the "keyword". But I need my script to start searching the file from line 100. Not from the beginning. I tried this, but it doesn't work.
<?php
$i=100;
$search = 'keyword';
$lines = file('mytextfile.txt');
foreach($lines as $line)
{
if($i>=120) break;
if(strpos($line, $search) !== false)
echo $line;
$i++;
}
?>
The script works but searches the file from the first line.
I also tried different script:
<?php
$ln = 0;
$start = 99;
$end = 119;
$fd = fopen('mytextfile.txt', 'r');
while(true) {
$line = fgets($fd);
if(!$line || $ln === $end + 1) {
break;
}
if($ln >= $start && $ln <= $end) {
echo $line;
}
$ln++;
}
fclose($fd);
?>
This script reads the file from line 100 to 120, but I don't know how to add a function to it to find only lines that contain a keyword. Can you help me?
I figured it out:
<?php
$keyword = 'keyword';
$lines = file('mytextfile.txt');
$lines = array_slice($lines, 100);
$i = 0;
foreach($lines as $line) {
if(strpos($line, $keyword) !== false){
echo $line;
$i++;
if ($i >= 20) {
break;
}
}
}
?>
Thank you very much miken32 for you help. I couldn't do it without you.