简体   繁体   English

PHP preg_match_all仅匹配最后一个元素

[英]Php preg_match_all matches only last element

I've this regex 我有这个正则表达式

{{([ a-zA-Z0-9_\-]+)\s*(?:\[([ a-zA-Z0-9_\-]+)\]\s*)*}}

and i need to match strings such as: 而且我需要匹配字符串,例如:

{{word with spaces}}
{{word with spaces [sub1]}}
{{word with spaces   [sub1]  [sub 2]  [Sub-3] }}

capturing word with spaces , and sub1 , sub 2 , Sub-3 . word with spacessub1sub 2Sub-3捕获word with spaces

The regex is working but the for the sub-s string matching gives only the last match, ie Sub-3 . 正则表达式正在工作,但sub-s字符串匹配的只能给出最后一个匹配,即Sub-3 How to get all sub1 , sub 2 , Sub-3 ? 如何获得所有sub1sub 2Sub-3 Thanks 谢谢

Here is another variant using \\G that is bit faster and avoids empty matches: 这是使用\\G另一种变体,它变快了一点并避免了空匹配:

(?:{{([\w-]+(?:\h+[\w-]+)*)|(?!\A)\G)(?:\h*\[([^]]+)]|\h*}})

RegEx Demo 正则演示

\\G asserts position at the end of the previous match or the start of the string for the first match. \\G在上一场比赛的末尾或首场比赛的字符串开头声明位置。

To get the value for sub in mulitple times group 2 you might use \\G to assert the position at the end of the previous match: 要获得多倍时间组2中的sub值,您可以使用\\G在上一个匹配项的末尾声明位置:

(?:{{([\w-]+(?: [\w-]+)*)|\G(?!$))(?:\h+\[([^]]+)\])?(?=.*})

Regex demo 正则表达式演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM