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-ph开发者_运维百科p -->
$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 $
)
$preg_match_all is what you want
$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_all("/^(\S+) (\S+) (\S+) \[([^:]+):(\d+:\d+:\d+) ([^\]]+)\] \"(\S+) (.*?) (\S+)\" (\S+) (\S+) (\".*?\") (\".*?\")$/", $lines[$i]['string'], $matches);
print_r($matches);
print '<br /><br />';
}
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.
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:
"/^(\S+) ... (\".*?\")$/s"
精彩评论