PHP 使用 RegEx 获取字符串的子串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5941832/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 22:58:18  来源:igfitidea点击:

PHP Using RegEx to get substring of a string

phpregexparsingsubstring

提问by MonkeyBlue

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.

我正在寻找一种使用 PHP 解析子字符串的方法,并且遇到了 preg_match 但是我似乎无法计算出我需要的规则。

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

736375493

Thanks Aaron

谢谢亚伦

回答by David Fells

$matches = array();
preg_match('/id=([0-9]+)\?/', $url, $matches);

This is safe for if the format changes. slandau's answer won't work if you ever have any other numbers in the URL.

如果格式更改,这是安全的。如果 URL 中有任何其他数字,slandau 的答案将不起作用。

php.net/preg-match

php.net/preg-match

回答by anubhava

<?php
$string = "producturl.php?id=736375493?=tm";
preg_match('~id=(\d+)~', $string, $m );
var_dump($m[1]); // $m[1] is your string
?>

回答by slandau

$string = "producturl.php?id=736375493?=tm";
$number = preg_replace("/[^0-9]/", '', $string);

回答by mickmackusa

Unfortunately, you have a malformed url query string, so a regex technique is most appropriate. See what I mean.

不幸的是,您有一个格式错误的 url 查询字符串,因此正则表达式技术是最合适的。见我的意思

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.

不需要捕获组。用 匹配id=然后忘记那些字符\K,然后隔离以下一个或多个数字字符。

Code (Demo)

代码(演示

$str = 'producturl.php?id=736375493?=tm';
echo preg_match('~id=\K\d+~', $str, $out) ? $out[0] : 'no match';

Output:

输出:

736375493