PHP preg_match_all:正则表达式通过转义获取管道分隔字段


PHP's preg_match_all: regex to get pipe-separeted fields with escaping

我已经问过如何使用管道转义从管道分隔的字符串中获取字符串字段,并得到了一个在 http://www.regex101.com 上效果很好的答案:一个正则表达式来获取管道分隔字符串的单个单词,支持管道转义。

不幸的是,这似乎在 PHP 的 preg_match_all() 函数中不起作用:

$input   = 'word1| word 2 |word'|3';
$pattern = '/(?P<w>(?:[^''|]+|'''|?)+)/';
$matches = array();
preg_match_all($pattern,$input,$matches);
// Expected $matches: $matches['w'] => array('word1', ' word 2 ', 'word'|3')

我错过了什么?该示例在这里工作正常:

https://regex101.com/r/zM7yV5/4

$re = "/(?P<w>(?:[^''''|]+|''''''|?)+)/";
$str = "word1| word 2 |word'|3";
preg_match_all($re, $str, $matches);