使用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线)?
答
它甚至跳过你都行,看 a demo on ideone.com.
在这里你去:
<?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.
答
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
使用'preg_match'而不是'preg_match_all' – cmorrissey