preg_match returns 只有一个(最后一个)结果
preg_match returns only one (last) result
我正在尝试使用 preg_match
函数解析此字符串以获取数组名称和所有索引:
{#array[index1][index2][index3] ... }
我试过这个正则表达式,但在 $matches
中只有最后一个索引 ([index3]
):
$string = "{#array[index1][index2][index3]}";
preg_match('|^\{\#[a-z0-9_\-]+(\[[a-z0-9_-]+\])*\}|i',$string,$matches);
结果:
Array
(
[0] => {#array[index1][index2][index3]}
[1] => [index3]
)
有人能帮帮我吗?
顺便说一句:preg_match_all
returns 结果相同
Preg_match确实只匹配一个。
如果您想用正则表达式匹配更多数据,您需要 preg_match_all。
您需要使用 \G
锚点才能进行连续的字符串匹配。
(?:\{#([a-z0-9_\-]+)|(?<!^)\G)\[([^\[\]]+)\](?=[^{}]*\})
我正在尝试使用 preg_match
函数解析此字符串以获取数组名称和所有索引:
{#array[index1][index2][index3] ... }
我试过这个正则表达式,但在 $matches
中只有最后一个索引 ([index3]
):
$string = "{#array[index1][index2][index3]}";
preg_match('|^\{\#[a-z0-9_\-]+(\[[a-z0-9_-]+\])*\}|i',$string,$matches);
结果:
Array
(
[0] => {#array[index1][index2][index3]}
[1] => [index3]
)
有人能帮帮我吗?
顺便说一句:preg_match_all
returns 结果相同
Preg_match确实只匹配一个。
如果您想用正则表达式匹配更多数据,您需要 preg_match_all。
您需要使用 \G
锚点才能进行连续的字符串匹配。
(?:\{#([a-z0-9_\-]+)|(?<!^)\G)\[([^\[\]]+)\](?=[^{}]*\})