模式匹配后打印x行数

时间:2018-07-31 10:05:17

标签: php regex

我有一个php代码,可在日志文件中浏览一个模式。找到模式后,我想在此之后打印接下来的几行。或者,如果我们可以捕获零件,直到遇到特定的图案。

将以如下方式找到日志文件的内容:

DEV   - 2018-07-10 03:10:22 --> --------------API CALL STARTS-------------
DEV   - 2018-07-10 03:10:22 --> ------------------------------------------
DEV   - 2018-07-10 03:10:22 --> -------------------------------------
DEV   - 2018-07-10 03:10:22 --> ----------- HEADERS START ----------------
DEV   - 2018-07-10 03:10:22 -->  
XYZ-DEVICE : XZY 
XYZ-DEVICE : XZY
XYZ-DEVICE : XZY

DEV   - 2018-07-10 03:10:22 --> ----------- HEADERS END ----------------
DEV   - 2018-07-10 03:10:22 --> ----------- API AND PARAMS START ---------------
DEV   - 2018-07-10 03:10:22 --> api.xyz.com/api/abc/xyz_get 
DEV   - 2018-07-10 03:10:22 -->  

DEV   - 2018-07-10 03:10:22 --> ----------- API AND PARAMS END ---------------
DEV   - 2018-07-10 03:10:22 --> -------------------------------------
DEV   - 2018-07-10 03:10:22 --> ------------------------------------------
DEV   - 2018-07-10 03:10:22 --> ---------------API CALL ENDS--------------

理想情况下,我希望从以下内容获取内容:

----------- HEADERS START ----------------

耕种

----------- API AND PARAMS END ---------------

所以我以后可以用它来进行api调用。

我当前的脚本找到了api调用,但是在匹配模式后它不会打印出内容。

$dir = "./log/"; 
if (is_dir($dir)) {
    if ($dh = opendir($dir)) {
        $counter = 1;
        while (($file = readdir($dh)) !== false) {
            if($file != '.' || $file != '..'){
                $searchfor = 'api.xyz.com/api/'; //pattern to search for

                // the following line prevents the browser from parsing this as HTML.
                header('Content-Type: text/plain');

                // get the file contents, assuming the file to be readable (and exist)
                $contents = file_get_contents($dir.'/'.$file);
                // escape special characters in the query
                $pattern = preg_quote($searchfor, '/');
                // finalise the regular expression, matching the whole line
                $pattern = "/^.*$pattern.*\$/m";
                // search, and store all matching occurences in $matches
                if(preg_match_all($pattern, $contents, $matches)){
                   echo "Found matches:\n";
                   echo $counter." - ".implode("\n", $matches[0]);
                   echo "\n";
                   $counter++;
                }
            }
        }
        closedir($dh);
    }
}

1 个答案:

答案 0 :(得分:0)

如果必须使用正则表达式,则可以在表达式中精确查找它:

$from="----------- HEADERS START ----------------";
$to="----------- API AND PARAMS END ---------------";
$pattern = "/$from.*?$to/gs"; 
//We do not want the m flag, so the entire block is caught. 
//Not sure you need the s flag but you migh

这会从$from$to /-https://regexr.com/3t84j(全部)(全部)返回。