Reputation: 295
For some reason my regex is matching what I am after and extra. I am needing to just match the group #
, but it's matching the first number of the phone numbers also.
Example data:
id: N group: 1 category: NAMES : Mike
id: N group: 2 category: NAMES : Seth
id: # group: 1 category: PHONE : 123-456-789
id: # group: 2 category: PHONE : 111 111-1111
id: @ group: 1 category: EMAIL : [email protected]
id: @ group: 2 category: EMAIL : [email protected]
Regex
preg_match_all('/:\s+\d/', $data, $matches);
Current output
1
2
1
1
2
1
1
2
Expected output
1
2
1
2
1
2
Upvotes: 1
Views: 98
Reputation: 70722
You can use the following, which will also exclude the whitespace and give you your exact match.
preg_match_all('/(?<![^ ])\d(?!\d)/', $data, $matches);
See live demo
Or to be safe, you could just use a look ahead.
preg_match_all('/\d(?= +category)/i', $data, $matches);
See live demo
Better yet, just simply match for group:
and the following number.
preg_match_all('/group:\s+\K\d/i', $data, $matches);
Upvotes: 1
Reputation: 350
Change your regular expression through
"/group:\s*(\d+)/i"
The issue is that you have also ":" after PHONE and EMAIL
Upvotes: 3
Reputation: 237845
You could do a lookahead, to make sure that category
follows immediately:
preg_match_all('/:\s+\d(?= category)/', $data, $matches);
The lookahead is not captured, but strings won't match if it isn't there.
Upvotes: 1