2

I am trying to parse the HTTP request with the following code:

$request="GET /index.html HTTP/1.1";
$methods="GET|HEAD|TRACE|OPTIONS";
$pattern="/(^".$methods.")\s+(\S+)\s+(HTTP)/";
list($method,$uri,$http)=preg_split($pattern,$request);
print $method.$uri.$http;

Print does not return anything. I tried different modifications,but wasn't able to. I think the problem is with the regex. Any help is appreciated.

2 Answers 2

5

Instead of preg_split(), you may want to use preg_match(), and move the ^ outside the parens.

$request="GET /index.html HTTP/1.1";
$methods="GET|HEAD|TRACE|OPTIONS";
$pattern="/^(".$methods.")\s+(\S+)\s+(HTTP)/";
//-------^^^^

$matches = array();
preg_match($pattern, $request, $matches);
print_r($matches);

// To get it back to the form you wanted...
array_shift($matches);
list($method, $uri, $http) = $matches;
Sign up to request clarification or add additional context in comments.

2 Comments

It doesn't matter whether the ^ is inside or outside the parentheses: it is a zero-width match and won't affect the result.
Don't put the method names into the regexp; there are more methods than these.
1

It would be simpler to simply split the request on whitespace.

list($method, $uri, $http) = preg_split('/\s+/', $request);

will produce the same result, except that $http will be HTTP/1.1 which may or may not be what you want in the first place.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.