n1nsa1d00
n1nsa1d00

Reputation: 876

Why is preg_match matching empty string when testing the following regex pattern?

I formed a regex pattern to match strings representing commands in the following format:

!<name of command>\s+<possible parameters separated with commas>

or

!<name of command>

The regex looks like this a the moment:

^!(\w+)\s+([\w,\s]+\w+)$|^!(\w+)$

When I use preg_match to test an eventual string against my pattern:

$res = "!add"
preg_match('~^!(\w+)\s+([\w,\s]+\w+)$|^!(\w+)$~',$res,$match);

the $match array returned has 4 unexpected entries.

array(4) {
[0]=>
string(11) "!addhhgnhgj"
[1]=>
string(0) ""
[2]=>
string(0) ""
[3]=>
string(10) "addhhgnhgj"
}

Two strangely match empty string and the other two match the full string and the third capture group (as I was expecting). When $res equals to "!add param1, param2", $match has exactly 3 entries as expected.

Why is the above happening when testing the string of a command followed by no parameters?

Upvotes: 1

Views: 224

Answers (1)

revo
revo

Reputation: 48711

Numbers are relative to capturing groups.

Your input string matches with second side of alternation ^!(\w+)$. It stores whole match at index 0 of output array and 1 and 2 indexes correspond to capturing groups of first side of alternation that are not captured and third contains something that is at index 3.

That is the reason for having 1 and 2 indexes empty.

^!(\w+)\s+([\w,\s]+\w+)$|^!(\w+)$
  --#1-   -----#2------    --#3-

Upvotes: 3

Related Questions