PHP preg_match匹配

时间:2013-06-10 17:37:06

标签: php preg-match

我正在尝试从字符串中获取所有匹配项:

$string = '[RAND_15]d4trg[RAND_23]';

使用这样的preg_match:

$match = array();
preg_match('#\[RAND_.*]#', $string, $match);

但在那之后$ match数组看起来像这样:

Array ( [0] => [RAND_15]d4trg[RAND_23] )

如何在$ match数组中将两次出现作为2个单独的元素?我想得到这样的结果:

$match[0] = [RAND_15];
$match[1] = [RAND_23];

1 个答案:

答案 0 :(得分:4)

使用......

$match = array();
preg_match_all('#\[RAND_.*?]#', $string, $match);

......相反。 ?修饰符会使模式变为“懒惰”,匹配最短的子字符串。没有它,模式将尝试覆盖可能的最大距离,从技术上讲,[RAND_15]d4trg[RAND_23] 匹配模式。

另一种方法是限制字符集与否定字符类匹配:

$match = array();
preg_match_all('#\[RAND_[^]]*]#', $string, $match);

这样我们就不必将量词变为懒惰,因为[^]]字符类将在第一个]符号处停止匹配。

尽管如此,要抓住所有匹配项,您应该使用preg_match_all而不是preg_match。这是说明差异的demo

相关问题