PHP:找到一个后回显2行

时间:2014-03-04 20:40:19

标签: php

<?php
$handle = fopen("wqer.txt", "r");
if ($handle) {
    while (($line = fgets($handle)) !== false) {
      if(preg_match("/aut/i", $line)){
      **echo fgets($handle).fgets($handle);**
      } 
    }
} else {
    echo "Error loading file.";
}
?>

文本文件wqer.txt看起来像那样(但它有12k行:D):

bike
*aut*
car
ball
mouse
*aut*
light
house

我希望此脚本在从此文件中找到 aut 行后回显下两行。 所以输出应该如下所示:

car
ball
light
house
对不起,房子应该是最后一个。 解决了,非常感谢Wrikken,简单的解决方案,我几乎感到尴尬:))

2 个答案:

答案 0 :(得分:2)

$found = 0;
while (($line = fgets($handle)) !== false) {
    if(preg_match("/aut/i", $line)){
       $found = 2;
       continue; // if you don't want "aut" to be printed. remove otherwise.
    }
    if ($found > 0) {
      echo $line;
      $found--;
    }
}

答案 1 :(得分:1)

添加错误检查:

$lines = file("wqer.txt", FILE_IGNORE_NEW_LINES);
$lines = array_map('trim', $lines); //in case there are spaces etc. that are not shown

foreach($lines as $key => $val) {
    if($val == '*aut*') {  //(stripos($val, 'aut') !== false) //to keep similar to how you have it now
        echo $lines[$key+1] . "\n" . $lines[$key+2] . "\n";
    }
}