我想知道如何创建preg_match捕获:
id=4
4是任何数字,如何在字符串中搜索上述示例?
如果这可能是正确/^id=[0-9]/的,我问的原因是因为我不太擅长preg_match。
我想知道如何创建preg_match捕获:
id=4
4是任何数字,如何在字符串中搜索上述示例?
如果这可能是正确/^id=[0-9]/的,我问的原因是因为我不太擅长preg_match。
对于 4 是任意数字,我们必须为其设置范围:
/^id\=[0-9]+/
\转义等号,数字后面的加号表示 1 甚至更多。
您应该使用以下内容:
/id=(\d+)/g
id=- 文字id=(\d+)- 捕获组0-9之间的字符范围0和9;+- 重复无限次/g- 修饰符:全局。所有比赛(第一场比赛不返回)如果您想在 PHP 中获取所有 id 及其值,您可以使用:
$string = "There are three ids: id=10 and id=12 and id=100";
preg_match_all("/id=(\d+)/", $string, $matches);
print_r($matches);
Array
(
[0] => Array
(
[0] => id=10
[1] => id=12
[2] => id=100
)
[1] => Array
(
[0] => 10
[1] => 12
[2] => 100
)
)
注意:如果你想匹配所有你必须使用/g修饰符。PHP 不支持它,但它具有其他功能,即preg_match_all. 您需要做的就是g从正则表达式中删除 。