如何排除 preg_split 正斜杠后跟用单引号括起来的字符串

How to exclude preg_split forward slash followed with string enclosed in single quote

如何排除 preg_split 正斜杠后跟用单引号括起来的字符串?

这个问题让我很受打击。

下面是代码,后面是输出。

$str =  "storeid='1,2',categoryname = 'the ultimate \'operating room'";

$match = preg_split("/('[^'\\]*')/U", $str, null, PREG_SPLIT_DELIM_CAPTURE);

print_r($match);

输出

Array ( [0] => storeid= [1] => '1,2' [2] => ,categoryname = 'the ultimate \ [3] => 'operating room' [4] => ) 

但这是我的预期输出,我想排除 \'。

希望有人理解并帮助我。

Array ( [0] => storeid= [1] => '1,2' [2] => ,categoryname =[3] =>  'the ultimate \'operating room'  ) 

在捕获单引号中的所有内容时,您还应该注意转义的单引号。按照这个正则表达式:

'[^'\\]*(?:\\.[^'\\]*)*'
  • '单引号(左)
  • [^'\\]* 除了 '\
  • 之外的所有字符
  • (?:\\.[^'\\]*)* 匹配转义字符(如果存在则尽可能匹配之前的模式)
  • ' 单引号(结束)

PHP:

$match = preg_split("/('[^'\\]*(?:\\.[^'\\]*)*')/",
    $str,
    -1,
    PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);

输出:

Array
(
    [0] => storeid=
    [1] => '1,\'2'
    [2] => ,categoryname = 
    [3] => 'the ultimate \'operating room'
)