使用PHP中的正则表达式读取文件并提取数据

时间:2016-08-03 18:05:02

标签: php regex

我试图回显用logfile.txt编写的文件的名称/路径。为此,我使用正则表达式来匹配:第一次出现之前的所有内容并输出它。我逐行阅读logfile.txt

<?php

$logfile = fopen("logfile.txt", "r");

if ($logfile) {
    while (($line = fgets($logfile)) !== false) {
        if (preg_match_all("/[^:]*/", $line, $matched)) {
            foreach ($matched as $val) {
                foreach ($val as $read) {
                    echo '<pre>'. $read . '</pre>';
                }
            }
        }
    }

    fclose($logfile);
} else {
    die("Unable to open file.");
}

?>

但是,我得到了文件的全部内容。所需的输出是:

/home/user/public_html/an-ordinary-shell.php
/home/user/public_html/content/execution-after-redirect.html
/home/user/public_html/paypal-gateway.html

以下是logfile.txt的内容:

-------------------------------------------------------------------------------

/home/user/public_html/an-ordinary-shell.php: Php.Trojan.PCT4-1 FOUND
/home/user/public_html/content/execution-after-redirect.html: {LDB}VT-malware33.UNOFFICIAL FOUND
/home/user/public_html/paypal-gateway.html: Html.Exploit.CVE.2015_6073

额外的问题:如何跳过阅读前两行(即破折号和emtpy行)?

2 个答案:

答案 0 :(得分:3)

你走了:

struct list_head

<小时/> 它甚至会跳过你的两行,请参阅a demo on ideone.com.

答案 1 :(得分:3)

preg_match_all返回模式的所有匹配项。对于第一行,它将返回:

/home/user/public_html/an-ordinary-shell.php,一个空字符串,Php.Trojan.PCT4-1 FOUND 和另一个空字符串

不包含:

要获得单个结果,请使用preg_match,但使用explode执行该操作就足够了。

要跳过您不想要的行,您可以构建一个只提供好行的generator function。您也可以使用流过滤器。