用于解析http请求的正则表达式

use*_*034 2 php regex http

我试图用以下代码解析HTTP请求:

$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;
Run Code Online (Sandbox Code Playgroud)

打印不返回任何内容.我尝试了不同的修改,但无法做到.我认为问题在于正则表达式.任何帮助表示赞赏.

Mic*_*ski 5

而不是preg_split(),你可能想要使用preg_match(),并移动到^外面的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;
Run Code Online (Sandbox Code Playgroud)