preg_match_all with space and comma delimiters
Asked Answered
S

1

1

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
Stereotypy answered 26/7, 2012 at 18:27 Comment(0)
H
2

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

Halophyte answered 26/7, 2012 at 18:28 Comment(7)
@Stereotypy - You were pretty close! The more you use it, the more familiar you will become with it.Halophyte
Unfortunately, every time I use it, it's a completely different scenario than last time, and lose what I've already managed to figure out, lol....having "Regex Power" would beat any Super Hero power in my book!Stereotypy
is there syntax to make the 2nd group optional, or better yet a default if it's not there?Stereotypy
Sure, just put a question mark after it. But, if you want it to be optional, you probably also want to omit the comma. So, I can edit my answer with a better regex to do that.Halophyte
I always want to send money when someone goes the extra mile like you are - yes, the 2nd group is optional, and would not have a comma if it were excluded.Stereotypy
Well, I'll nominate you for the Regex Emmy awards when it's time - thanks so very much, and most especially for the added explanation of how it comes together.Stereotypy
@Stereotypy - Hah! Sounds good to me. Not a problem, glad I could help!Halophyte

© 2022 - 2024 — McMap. All rights reserved.