PHP的preg_match_all:正则表达式以获取带有转义的管道分区字段

时间:2015-01-29 12:49:29

标签: php regex

我已经问过question如何通过管道转义从管道分隔的字符串中获取字符串字段,并得到一个在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

1 个答案:

答案 0 :(得分:1)

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

preg_match_all($re, $str, $matches);