我正在使用 php 的 preg_split根据分号拆分字符串,但我需要它只拆分非转义分号。
<?
$str = "abc;def\\;abc;def";
$arr = preg_split("/;/", $str);
print_r($arr);
?>
产生:
Array
(
[0] => abc
[1] => def\
[2] => abc
[3] => def
)
当我想要它产生时:
Array
(
[0] => abc
[1] => def\;abc
[2] => def
)
我试过 "/(^\\)?;/"
或 "/[^\\]?;/"
但它们都会产生错误。有什么想法吗?
最佳答案
这有效。
<?
$str = "abc;def\;abc;def";
$arr = preg_split('/(?<!\\\);/', $str);
print_r($arr);
?>
输出:
Array
(
[0] => abc
[1] => def\;abc
[2] => def
)
您需要使用负向回顾 (read about lookarounds)。想想“全部匹配”;除非前面有 '\'"。
关于php - 用于拆分所有未转义分号的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2099871/