preg_match_all 带空格
有一些标题,例如:
HTTP/1.1 100 Continue
HTTP/1.1 302 Found
HTTP/1.1 200 OK
HTTP/1.1 400 Not Found
所以,我需要获取两部分:
[200] => [OK]
[400] => [Not Found]
我需要一种使用 preg_match_all
并获取这些值的方法,但需要保留 Not Found
处的
空格此代码:
preg_match_all( '/([0-9]{3}) ([A-Za-z0-9+]*)/', $headers, $matches );
适用于 1-3 个示例标头。
有什么想法吗?
have some headers like:
HTTP/1.1 100 Continue
HTTP/1.1 302 Found
HTTP/1.1 200 OK
HTTP/1.1 400 Not Found
so, I need to get 2 parts:
[200] => [OK]
[400] => [Not Found]
I need a way to use preg_match_all
and get those values, but need to preserve the spaces at Not Found
have this code:
preg_match_all( '/([0-9]{3}) ([A-Za-z0-9+]*)/', $headers, $matches );
Works with 1-3 example headers.
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

发布评论
评论(3)
欲拥i2025-01-11 07:08:17
您可以使用 (?P
为您的正则表达式匹配指定一个名称,使您的代码更具可读性。您还可以使用更简单的正则表达式:
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
云之铃。2025-01-11 07:08:17
您使用的正则表达式几乎很好,但字符组定义中缺少 [ ]
(空格),它应该是: /([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 );
<一个href="http://www.php.net/manual/en/regexp.reference.escape.php" rel="nofollow">这是转义序列的解释。
~没有更多了~
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
对于单行和一般文本
那么,您是否将每个标题放在新行上?
For the single line and for the text in general
So, do you have each header on a new line or not?