【发布时间】:2016-12-22 06:06:48
【问题描述】:
我正在尝试从混合字符串中提取数字。
<?php
$string = "c <a data-player-id=\"5528\" href=\"/players/5528-ga-name--5406546\" target=\"_self\">GA Name</a> b <a data-player-id=\"8992842\" href=\"/players/8992842-chandran-win--123345\" target=\"_self\">C Win</a>";
//preg_match_all('!\d+!', $string, $matches);
//preg_match_all('/data-player-id=\"(\d+)/', $string, $matches);
preg_match_all('/\/players\/(\d+)/', $string, $matches);
print_r($matches);
?>
但它会产生 2 个数组:
Array
(
[0] => Array
(
[0] => /players/5528
[1] => /players/8992842
)
[1] => Array
(
[0] => 5528
[1] => 8992842
)
)
我想捕获像5528 和8992842 这样的数字。下面的代码不起作用。
/*
$zero = $matches[0];
$one = $matches[1];
$two = $matches[2];
echo $zero;
echo $one;
echo $two;
*/
编辑:
知道为什么它会返回 2 个数组吗?
array[1]里面的物品可以统计吗?
【问题讨论】:
-
echo $matches[1][0];和echo $matches[1][1]; -
如前所述,原因是您使用capturing group 进行提取。
$matches[1]始终包含第一个带括号的组(捕获组)的匹配项,$matches[0]包含完整的模式匹配项。通过使用报告匹配的开头\Kwhich resets 可以在不捕获组的情况下执行此操作,因此仅返回$matches[0]see this demo at regex101 中的数字。要计算它们,只需使用count($matches[0])。
标签: php preg-match preg-match-all preg-grep