Reputation: 2001
I have a simple regex, but it's matching more than I want...
Basically, I'm trying to match certain operators (eg. >
<
!=
=
) followed by a string.
Regex:
/^(<=|>=|<>|!=|=|<|>)(.*)/
Example subject:
>42
What I'm getting:
array (size=3)
0 => string '>42' (length=3)
1 => string '>' (length=1)
2 => string '42' (length=2)
What I'm trying to get:
array (size=2)
0 => string '>' (length=1)
1 => string '42' (length=2)
What I don't understand is that my regex works perfectly on Regex101
Edit: To clarify, how can I get rid of the full string match?
Upvotes: 0
Views: 166
Reputation: 47874
Not only will sscanf()
return the exact desired flat array, it will cast that number (after the comparison symbols) as an integer. If a float is possible, use %f
instead if %d
.
Code: (Demo)
var_export(
sscanf('>42', '%[<=>!]%d')
);
Upvotes: 0
Reputation: 5890
You are getting all 3 groups \0
, \1
, and '\2'. see the group matching at the bottom of the page
assuming your matches are in $matches
you can run array_shift($matches)
to remove the '\0' match if you wish.
Upvotes: 1
Reputation: 67968
Your answer is correct.Group(0)
is the whole match
.Group(1)
if first group and group(2)
is the second group.
Upvotes: 2