MacMan
MacMan

Reputation: 933

PHP regex matching multiple entries?

I'm parsing a log file line by line.

I want to match on the following :

"GET /manager/ HTTP/1.1" 200
"GET /manager HTTP/1.1" 200
"GET /manager HTTP/1.1" 401
"GET /manager/ HTTP/1.1" 401

Currently I'm assigning each of these options to it's own variable, then doing :

if (strpos($line,$a) || strpos($line,$b) || strpos($line,$c) || strpos($line,$d)) 
    {
    }

if there a better way ? thanks

Upvotes: 2

Views: 245

Answers (3)

Garfield
Garfield

Reputation: 2537

Try this regex (GET|POST)\s+(.*)\s+(HTTP.*)\s+(\d{3}) This will give you ["GET", "/manager/", "HTTP/1.1", "401"]

Updated code:

$logStr = '"GET /manager/ HTTP/1.1" 200
"GET /manager HTTP/1.1" 200
"GET /manager HTTP/1.1" 401
"GET /manager/ HTTP/1.1" 401
';
echo $logStr;
preg_match('/(GET|POST)\s+(.*)\s+(HTTP.*)\s+(\d{3})/', $logStr, $matches);
print_r($matches);

Upvotes: 0

Winston
Winston

Reputation: 1805

Try it

$str = '
"GET /manager/ HTTP/1.1" 200
"GET /manager HTTP/1.1" 200
"GET /manager HTTP/1.1" 401
"GET /manager/ HTTP/1.1" 401
';

preg_match_all('#^\s*("GET\s+/manager/?\s+HTTP/1\.1"\s+(?:200|401)+)#im', $str, $match);
print_r($match[1]);

Upvotes: 0

Jon
Jon

Reputation: 437654

This regular expression will match all four variations:

^"GET /manager/? HTTP/1\.1" (200|401)$

You will also have to escape the slashes with a backslash unless you use another character as the delimiter.

Upvotes: 4

Related Questions