preg_match_all with space and comma delimiters

可紊 提交于 2019-12-11 04:43:11

问题


I've managed to get part of the preg_match returning the values I need, but am unable to get the correct syntax to return what follows that string after a comma. Any assistance is appreciated - thanks

$regex = '{loadsegment+(.*?)}';
$input = '{loadsegment 123,789}';
preg_match_all($regex, $input, $matches, PREG_SET_ORDER);

Current result :

$matches [0] [0] {loadsegment 123}
             [1] 123,789

Desired result :

$matches [0] [0] {loadsegment 123,789}
             [1] 123
             [2] 789

回答1:


You need two capturing groups before and after a comma (and delimiters):

$regex = "/{loadsegment (\d+),(\d+)}/";

Also, I'm using \d which is shorthand for a digit, instead of .*?, which is anything.

I also removed t+ for t, since t+ will match t one or more times, which doesn't seem like what you want to do.

To make the second group optional, you'd use the ? modifier:

/{loadsegment (\d+),(\d+)?}/

But this still requires the comma. You can make it optional as well...

/{loadsegment (\d+),?(\d+)?}/

... but now your regex will match:

{loadsegment 123,}

which we probably dont want. So, we include the comma in the optional second group, like this:

/{loadsegment (\d+)(?:,(\d+))?}/

Explanation (minus the delimiters):

{loadsegment   - Match "{loadsegment "
(\d+)          - Match one or more digits, store in capturing group 1
(?:            - Non-capturing group (so this won't be assigned a capturing group number
    ,          - Match a comma
    (\d+)      - Match one or more digits, store in capturing group 2
)
?              - Make the entire non-capturing group optional

Demo at RegExr



来源:https://stackoverflow.com/questions/11675691/preg-match-all-with-space-and-comma-delimiters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!