从格式错误的查询字符串中获取整数值
我正在寻找一种使用 PHP 解析子字符串的方法,并且遇到了 preg_match 但是我似乎无法找出我需要的规则。
我正在解析一个网页,需要从字符串中获取一个数值,字符串是这样的
producturl.php?id=736375493?=tm
我需要能够获取字符串的这一部分:
736375493
I'm looking for an way to parse a substring using PHP, and have come across preg_match however I can't seem to work out the rule that I need.
I am parsing a web page and need to grab a numeric value from the string, the string is like this
producturl.php?id=736375493?=tm
I need to be able to obtain this part of the string:
736375493
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果格式发生变化,这是安全的。如果您的网址中有任何其他数字,slandau 的答案将不起作用。
php.net/preg-match
This is safe for if the format changes. slandau's answer won't work if you ever have any other numbers in the URL.
php.net/preg-match
不幸的是,您有一个格式错误的 URL 查询字符串,因此正则表达式技术是最合适的。请参阅我的意思。
不需要捕获组。只需匹配
id=
,然后用\K
忘记这些字符,然后隔离出后面的一个或多个数字字符。代码(演示)
输出:
为了完整起见,还有另一种方法来扫描 <格式化字符串并显式返回 int 类型值。 (Demo)
%*[^?]
表示:贪婪地匹配一个或多个非问号字符,但不捕获子字符串。格式参数的其余部分与文字序列?id=
匹配,然后贪婪地捕获一个或多个数字。由于%d
占位符,返回值将被转换为整数。Unfortunately, you have a malformed URL query string, so a regex technique is most appropriate. See what I mean.
There is no need for capture groups. Just match
id=
then forget those characters with\K
, then isolate the following one or more digital characters.Code (Demo)
Output:
For completeness, there is another way to scan the formatted string and explicitly return an int-typed value. (Demo)
The
%*[^?]
means: greedily match one or more non-question mark characters, but do not capture the substring. The remainder of the format parameter matches the literal sequence?id=
, then greedily captures one or more numbers. The returned value will be cast as an integer because of the%d
placeholder.