循环内的 Preg_match 问题
我正在尝试使用 for 循环对字符串数组执行 preg_match
,但它仅返回数组中最后一项的过滤结果。
这是我的代码:
$file = "smalllog";
$handle = fopen($file, 'rb');
if ($handle) {
$lines = array();
$count = 0;
while ( ($line = fgets($handle)) !== false) {
if(strpbrk($line,"/tracking/p2x/")) {
$lines[$count]['string'] = $line;
$count++;
}
}
fclose($handle);
}
for($i=0;$i<count($lines);$i++) {
$matches = array();
preg_match("/^(\S+) (\S+) (\S+) \[([^:]+):(\d+:\d+:\d+) ([^\]]+)\] \"(\S+) (.*?) (\S+)\" (\S+) (\S+) (\".*?\") (\".*?\")$/", $lines[$i]['string'], $matches);
print_r($matches);
print '<br /><br />';
}
应该显示分解数组的列表。然而我实际看到的更像是这样的:
Array()
Array()
Array (!--在这里正确分解数据--!)
如果这是一个愚蠢的问题,我深表歉意 - 我的 PHP 技能不太好。
编辑:以下更改似乎纠正了该问题:
将正则表达式从:更改
"/^(\S+) (\S+) (\S+) \[([^:]+):(\d+:\d+:\d+) ([^\]]+)\] \"(\S+) (.*?) (\S+)\" (\S+) (\S+) (\".*?\") (\".*?\")$/"
为:(
"/^(\S+) (\S+) (\S+) \[([^:]+):(\d+:\d+:\d+) ([^\]]+)\] \"(\S+) (.*?) (\S+)\" (\S+) (\S+) (\".*?\") (\".*?\")/"
删除了$
)
I'm trying to do a preg_match
on an array of strings using a for loop but it's only returning the filtered result for the final item in the array.
Here is my code:
<!-- language: lang-php -->
$file = "smalllog";
$handle = fopen($file, 'rb');
if ($handle) {
$lines = array();
$count = 0;
while ( ($line = fgets($handle)) !== false) {
if(strpbrk($line,"/tracking/p2x/")) {
$lines[$count]['string'] = $line;
$count++;
}
}
fclose($handle);
}
for($i=0;$i<count($lines);$i++) {
$matches = array();
preg_match("/^(\S+) (\S+) (\S+) \[([^:]+):(\d+:\d+:\d+) ([^\]]+)\] \"(\S+) (.*?) (\S+)\" (\S+) (\S+) (\".*?\") (\".*?\")$/", $lines[$i]['string'], $matches);
print_r($matches);
print '<br /><br />';
}
Which should display a list of exploded arrays. However what i actually see looks more like this:
Array()
Array()
Array ( !--correctly exploded data in here--! )
I apologize if this is a dumb question - my PHP skills are not great.
EDIT: Here is the change that seems to have corrected the issue:
Changing the regexp from:
"/^(\S+) (\S+) (\S+) \[([^:]+):(\d+:\d+:\d+) ([^\]]+)\] \"(\S+) (.*?) (\S+)\" (\S+) (\S+) (\".*?\") (\".*?\")$/"
to:
"/^(\S+) (\S+) (\S+) \[([^:]+):(\d+:\d+:\d+) ([^\]]+)\] \"(\S+) (.*?) (\S+)\" (\S+) (\S+) (\".*?\") (\".*?\")/"
(dropped the $
)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
$preg_match_all 就是你想要的
$preg_match_all is what you want
您正在使用 strpbrk() 完全错误的 strpbrk 期望它的第二个参数是字符列表,显然您正在尝试用它搜索字符串。为此,请使用 strpos() 。
You are using strpbrk() completely wrong strpbrk expects its second argument to be a character list, you are obviously trying to search for a string with it. Use strpos() for that.
您的行末尾有 \n 字符(最后一行除外),并且由于正常的 .* 不匹配 \n 您的模式不匹配。您需要使用 DOTALL 修饰符,将“s”添加到模式末尾(分隔符之后),应该没问题:
You have \n character at the end of your lines (except the last line) and since normal .* doesn't match \n your pattern doesn't match. You need to use the DOTALL modifier, add "s" to the end of your pattern (after the delimiter) and you should be fine: