PHP正则表达式尝试匹配数字时出现问题
我对 PHP 中的正则表达式有疑问。
我正在尝试查找通过 CURL 收到的某些标头数据的匹配项。但是,我的正则表达式匹配两行,而不是一行。
下面是我的正则表达式模式:
/^(http\/\d\.\d)\s+(100)\s+([\w\-\s\/\'\"\(\)\\\.]+)$/im
这是我尝试匹配的字符串:
HTTP/1.1 100 Continue
HTTP/1.1 201 Created
Content-Length: 118
Content-Type: text/html; charset=UTF-8
Etag: 8c59b7e37f672374c61245c8115f53d0
Last-Modified: Tue, 16 Aug 2011 20:24:10 GMT
X-Trans-Id: txd6cbafcec90d4e30b2a108ff3157c1b1
Date: Tue, 16 Aug 2011 20:24:10 GMT
它应该与第一行匹配,但我得到了 100 和 201 的匹配。我不明白为什么它这样做。
顺便说一句,我正在使用 preg_match 。
关于如何解决这个问题有什么想法吗?谢谢。
I have an issue with regular expressions in PHP.
I'm trying to find a match for some header data that I received via CURL. However, my regex is matching two lines, instead of one.
Below is my regex pattern:
/^(http\/\d\.\d)\s+(100)\s+([\w\-\s\/\'\"\(\)\\\.]+)$/im
And here is the string I'm trying match:
HTTP/1.1 100 Continue
HTTP/1.1 201 Created
Content-Length: 118
Content-Type: text/html; charset=UTF-8
Etag: 8c59b7e37f672374c61245c8115f53d0
Last-Modified: Tue, 16 Aug 2011 20:24:10 GMT
X-Trans-Id: txd6cbafcec90d4e30b2a108ff3157c1b1
Date: Tue, 16 Aug 2011 20:24:10 GMT
It's supposed to match the first line but I'm getting a match for both 100 and 201. I can't understand why it's doing this.
I'm using preg_match by the way.
Any ideas as to how I can solve this? Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
更新:
多行修饰符与真正的原因正交。您的问题是字符类定义(方括号之间的字符类定义)包含
\s
,它匹配任何空白字符,包括换行符。在本例中将其替换为实际的空格,以匹配该空格。顺便说一句,如果您有权在服务器上安装扩展,您可能需要使用
pecl_http
扩展用于解析 http,而不是手动完成。Update:
The multiline modifier is orthogonal to the real cause. Your problem is that the character class definition (That between the square brackets) includes
\s
, which matches any whitespace character, including linebreaks. Replace it with an actual space in this case, to match just that.As an aside, if you have access to install extensions on your server, you might want to use the
pecl_http
extension for parsing http, rather than doing it by hand.@troelskn 是对的,但是您也可以要求 CURL 告诉您 HTTP 响应代码:
编辑:而不是:
尝试 (RegexPal):
@troelskn is right, however you can also ask CURL to tell you the HTTP response code:
EDIT: Instead of:
Try (RegexPal):