php - 用于拆分所有未转义分号的正则表达式

标签 php regex preg-replace

我正在使用 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/

相关文章:

php - 为从另一个查询中提取的每条记录运行一个新查询

php - 你能告诉我如何用正则表达式替换吗

PHP preg 替换白帽字符

c# - 如何替换字符串中的未知字符?通配符?

php - substr() 到 preg_replace() 匹配 php

php - 将我的加密库从 Mcrypt 升级到 OpenSSL

php - 将 SQL 转换为 JSON 并保留空值?

php - 有没有简单的方法来检索 Google 财经数据?

regex - 正则表达式之间的距离

javascript - 正则表达式删除 json 属性