来自 PHP 文档
J (PCRE_INFO_JCHANGED)
The (?J) internal option setting changes the local PCRE_DUPNAMES option.
Allow duplicate names for subpatterns.
因此 J 修饰符允许命名捕获组中出现重复的名称。比赛信息见右侧this演示。
当我尝试在 php 中检查此修饰符时,它会显示以下警告,并且不会显示任何输出。
PHP Warning: preg_match_all(): Unknown modifier 'J'
这是我的代码,
$str = "foobarbuzxxxxx";
preg_match_all('~(?<name>foo).*?(?<name>buz)~J', $str, $match);
print_r($match);
然后我可以通过添加 J
来解决这个问题正则表达式本身中的修饰符,例如,
'~(?J)(?<name>foo).*?(?<name>buz)~'
$str = "foobarbuzxxxxx";
preg_match_all('~(?J)(?<name>foo).*?(?<name>buz)~', $str, $match);
print_r($match);
输出:
Array
(
[0] => Array
(
[0] => foobarbuz
)
[name] => Array
(
[0] => buz
)
[1] => Array
(
[0] => foo
)
[2] => Array
(
[0] => buz
)
)
你看到name
了吗?是仅第二组而不是第一组的索引。但我们将两者定义在同一个名称下。在 this它清楚地表明有两个不同的组具有相同的名称,称为 name
。但在 php 中,print_r($match['name']);
仅打印第二组
Array
(
[0] => buz
)
但不是第一个。为什么?我假设如果我们这样做print_r($match['name']);
,它将显示两个但不显示第一个。
所以我关于使用 J
的两个问题PHP 中的修饰符是,
为什么它引用第二组而不是两者?如果它始终引用最后一个组,那么捕获组中需要重复的名称吗?
还有为什么要添加
J
php 分隔符显示警告后的修饰符(不起作用)?
最佳答案
因为数组不能包含两个相等的键。这就是为什么“name”键排在第一位,但具有最后一个值(已重新分配)。
Currently you can only use PCRE_INFO_JCHANGED by (?J) in the pattern. I have suggested times ago to the maintainer, but it wasn't accept the addiction of 'J' as valid modifier in the extension.
使用此修饰符的示例
preg_match_all('/(?J)(?<string>.*)1|(?<string>.*)2|(?<string>.*)3$/', "text2\npext3", $matches, PREG_SET_ORDER);
var_dump($matches);
preg_match_all('/(?J)(?<string>.*)1|(?<string>.*)2|(?<string>.*)3$/', "text2\npext3", $matches);
var_dump($matches);
关于php - 如何在php中使用J修饰符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28390779/