首页 > 解决方案 > 如何使用 PHP 从文件中查找多行?

问题描述

我正在编写一个 PHP 脚本来搜索 pcap 文件中的几行。这个 pcap 文件将通过 tail -> PHP 传输。

我需要找到几行,例如 (Host: www.google.com) 或 (Domain: amazon.com) 等。

我是 PHP 新手,正在努力让这段代码正常工作,所有获取的数据的实际输出都需要插入到 SQL DB 中。我已经使用正则表达式从 pcap 中过滤掉二进制内容。

我已经尝试了多个循环,例如 wile、foreach、for,但我不知道如何在我的脚本中执行此操作。

我到目前为止的代码是:

<?php

$handle = fopen('php://stdin', 'r');
$line = fgets ($handle, 1000);

$search1 = 'Location';
$search2 = 'Host:';
$search3 = 'User';
$search4 = 'Cookie';
$search5 = 'Domain:';

$matches = array();

$regex = '/[^a-zA-Z0-9\s\D\#$%^&*()+=\-\[\]\';,.\/{}|":<>?~\\\\]/';

if ($handle){
    while ($handle) {
        $buffer = fgets($handle);
        if(strpos($buffer, $search1) !== FALSE) {
            $res = preg_replace($regex, "", $buffer);
            $matches[] = $res;
            print_r($res). "\n";
        }
    } 
    fclose($handle);
}
?>

我在互联网上阅读了很多帖子,但找不到任何解决方案,或者我没有足够的 PHP 知识来完成这项工作。谁能帮我这个?

标签: php

解决方案


如果它首先工作,然后循环它总是考虑算法

$handle = fopen('php://stdin', 'r');
$line = fgets ($handle, 1000);

$search = ['Location','Host:','User','Cookie','Domain:'];
$matches = array();
$regex = '/[^a-zA-Z0-9\s\D\#$%^&*()+=\-\[\]\';,.\/{}|":<>?~\\\\]/';

if ($handle){
    while ($handle) {
        $buffer = fgets($handle);
        foreach($search as $seek){
            if(strpos($buffer, $seek) !== FALSE) {
                $res = preg_replace($regex, "", $buffer);
                $matches[] = $res;
                print_r($res). "\n";
            }
        }

    } 
    fclose($handle);
}
?>

推荐阅读