2012-02-09 36 views
1

有一些标题,如:preg_match_all用空格

HTTP/1.1 100 Continue 
HTTP/1.1 302 Found 
HTTP/1.1 200 OK 
HTTP/1.1 400 Not Found 

所以,我需要得到2个部分:

[200] => [OK] 
[400] => [Not Found] 

我需要一种方法来使用preg_match_all和获取这些值,但需要保留在Not Found

的空间有这样的代码:

preg_match_all('/([0-9]{3}) ([A-Za-z0-9+]*)/', $headers, $matches); 

适用于1-3示例标题。

任何想法?

+0

如果需要,我有一组这样的状态码。 – 2012-02-09 19:37:22

+2

如果每一个都是它自己的行/输入,你可以使用explode()的限制: 'list($ http,$ status,$ msg)= explode('',$ line,3);' – Wiseguy 2012-02-09 19:38:01

+1

不需要'preg_match_all'。有了这个结构,爆炸就足够了。 – Josh 2012-02-09 19:38:56

回答

3

对于单行和一般

$str = "HTTP/1.1 100 Continue 
HTTP/1.1 302 Found 
HTTP/1.1 200 OK 
HTTP/1.1 400 Not Found"; 

// for the values in the string, one on each line 
preg_match_all('#(\d{3})\s+([\w\s]+)$#m', $str, $matches); 
var_dump($matches); // captures a new line symbol if exists 

// for single value in the string 
$str = "HTTP/1.1 400 Not Found"; 
preg_match('#(\d{3})\s+([\w\s]+)$#', $str, $matches); 
var_dump($matches); 

所以文字,你有一个新行或不每一头?

+0

那些“#”字符是什么?不应该是正斜杠? – 2012-02-09 19:37:49

+1

@jperovic它可以是任何东西,只是习惯的问题。 – Cheery 2012-02-09 19:38:19

+0

哦,我不知道 - 谢谢! – 2012-02-09 19:40:18

3

你可以给你的正则表达式匹配一个名字(?P<name>),使你的代码更具可读性。

preg_match('#HTTP/1\.\d (?P<code>\d{3}) (?P<text>.*)#', $str, $matches); 
echo $matches['code']; // 2100", same as $matches[1] 
echo $matches['text']; // "Continue", same as $matches[2] 

preg_match_all('#HTTP/1\.\d (?P<code>\d{3}) (?P<text>.*)#', $str, $matches, PREG_SET_ORDER); 
echo $matches[0]['code']; // 100 
echo $matches[0]['text']; // Continue 
echo $matches[3]['code']; // 404 
echo $matches[3]['text']; // Not Found 

或更简单的使用explode(),没有正则表达式::你也可以用更简单的正则表达式去

list(,$code,$text) = explode(" ", $str, 3); // works only on a single status line 
echo $code; // 100 
echo $text; // Continue 
+0

谢谢你,要尝试非正则表达式... – greenbandit 2012-02-09 19:53:30

2

您使用几乎良好的正则表达式,但你缺少[ ](空间)从字符组定义,它应该是:/([0-9]{3}) ([A-Za-z0-9 +]*)/

或者说使用

  • \w而不是[A-Za-z]
  • \d而不是[0-9]
  • \s而不是[ ]

所以,你的行话看起来像:

/(\d{3}) ([\w\d\s+]*)/ 

,并确保它不会匹配的东西不应该

/HTTP\/1\.\d (\d{3}) ([\w\d\s+]+)/ 

所以整个代码看起来像:

preg_match_all('/HTTP\/1\.\d (\d{3}) ([\w\d\s+]+)/', $headers, $matches); 

Here's an explanation转义序列。

+0

谢谢队友,现在我在读。 – greenbandit 2012-02-09 19:52:26