php - 如何在php中使用J修饰符?

标签 php regex

来自 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 中的修饰符是,

  1. 为什么它引用第二组而不是两者?如果它始终引用最后一个组,那么捕获组中需要重复的名称吗?

  2. 还有为什么要添加 J php 分隔符显示警告后的修饰符(不起作用)?

最佳答案

  1. 因为数组不能包含两个相等的键。这就是为什么“name”键排在第一位,但具有最后一个值(已重新分配)。

  2. https://bugs.php.net/bug.php?id=47456

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);

http://3v4l.org/fnm76#v446

关于php - 如何在php中使用J修饰符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28390779/

相关文章:

php - 将文本框内容回显到 POST 请求中不起作用

ruby - 是否可以连接两个正则表达式变量?

php - 将 PHP 设置传递给 Javascript 的最佳方式是什么?

python - 在 Python 中从包含特殊字符的 CSV 单元格中提取字符串

java - 在 Cucumber 步骤定义上传递多个参数

regex - Netbeans - 复制突出显示的正则表达式搜索结果

Python Regex,re.sub,替换模式的多个部分?

php - Woocommerce 获取购物车项目元数据

php - mysql_close() 是必要的吗?

javascript - 如何将 PHP JSON 转换为 JS 数组