From the php docs
J (PCRE_INFO_JCHANGED)
The (?J) internal option setting changes the local PCRE_DUPNAMES option.
Allow duplicate names for subpatterns.
So J modifer allows duplicate names in the named captruing groups. See the match information at the right side in this demo.
When i'm trying to check this modifier in php, it displays the below warning and it won't display any output.
PHP Warning: preg_match_all(): Unknown modifier 'J'
Here is my code,
$str = "foobarbuzxxxxx";
preg_match_all('~(?<name>foo).*?(?<name>buz)~J', $str, $match);
print_r($match);
Then i able to solve this problem by adding the J
modifier in the regex itself like,
'~(?J)(?<name>foo).*?(?<name>buz)~'
$str = "foobarbuzxxxxx";
preg_match_all('~(?J)(?<name>foo).*?(?<name>buz)~', $str, $match);
print_r($match);
Output:
Array
(
[0] => Array
(
[0] => foobarbuz
)
[name] => Array
(
[0] => buz
)
[1] => Array
(
[0] => foo
)
[2] => Array
(
[0] => buz
)
)
did you see that the name
is an index for only the second group not the first group. But we define both under a single name. In this it clearly shows that there are two different groups with same name called name
. But in php, print_r($match['name']);
prints only the second group
Array
(
[0] => buz
)
But not the first one. Why? I assumed that if we do print_r($match['name']);
, it would display the both but not the first.
So my two questions regarding the use of J
modifier in PHP are,
Why it refer the second group instead of both? If it always refers to the last group then what's the need for duplicate names in the capturing groups?
And also why adding the J
modifier after the php delimiters displays warning (not working)?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…