PHP正则表达式尝试匹配数字时出现问题

发布于 2024-11-30 01:57:09 字数 619 浏览 0 评论 0原文

我对 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

§普罗旺斯的薰衣草 2024-12-07 01:57:09

更新:

多行修饰符与真正的原因正交。您的问题是字符类定义(方括号之间的字符类定义)包含 \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.

提笔书几行 2024-12-07 01:57:09

@troelskn 是对的,但是您也可以要求 CURL 告诉您 HTTP 响应代码:

$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

编辑:而不是:

/^(http\/\d\.\d)\s(100)\s([\w\-\s\/\'\"\(\)\\\.]+)$/im

尝试 (RegexPal):

/^(http\/\d\.\d)\s(100)\s([\w\-\s\/\'\"\(\)\\\.]+?)$/im

@troelskn is right, however you can also ask CURL to tell you the HTTP response code:

$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

EDIT: Instead of:

/^(http\/\d\.\d)\s(100)\s([\w\-\s\/\'\"\(\)\\\.]+)$/im

Try (RegexPal):

/^(http\/\d\.\d)\s(100)\s([\w\-\s\/\'\"\(\)\\\.]+?)$/im
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文