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

问题描述:

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

<?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线)?

+0

使用'preg_match'而不是'preg_match_all' – cmorrissey

在这里你去:

<?php 
# load it as a string 
$data = @file("logfile.txt"); 

# data for this specific purpose 
$data = <<< DATA 
------------------------------------------------------------------------------- 

/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 
DATA; 

$regex = '~^(/[^:]+):~m'; 
#^- anchor it to the beginning 
#/- a slash 
# ([^:]+) capture at least anything NOT a colon 
# turn on multiline mode with m 

preg_match_all($regex, $data, $files); 
print_r($files); 
?> 


它甚至跳过你都行,看 a demo on ideone.com.

+0

我会喜欢这个答案,但它会输出两个数组。第一个包含':',第二个在文件名之前没有斜杠开始。 – McJohnson

+0

你需要斜杠吗?更新答案,循环'$ files [1]'来获得你的文件。另外更新了ideone.com演示。 – Jan

+0

让我们说,我这样做。只是因为它们存在于文件中,最后我可能需要它们来处理特定情况。但我也想只有一个数组。 – McJohnson

preg_match_all返回所有出现的模式。对于第一线,它将返回:

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

不包含:

要获得单个结果,请使用preg_match,但要使用explode就足够了。

要跳过你不想要的行,你可以建立一个generator function,它只给出好的行。您也可以使用流过滤器。

+0

傻我。我忘了'preg_match_all'和'preg_match'之间的区别。它与'preg_match'并爆炸。感谢您的时间。我也会接受你的答案,但我只能接受你的答案。 – McJohnson