【问题标题】:Regexp tip request正则表达式提示请求
【发布时间】:2012-11-01 02:10:57
【问题描述】:

我有一个类似的字符串

"first,second[,b],third[a,b[1,2,3]],fourth[a[1,2]],sixth"

我想把它炸成数组

Array (
    0 => "first",
    1 => "second[,b]",
    2 => "third[a,b[1,2,3]]",
    3 => "fourth[a[1,2]]",
    4 => "sixth"
}

我试图删除括号:

preg_replace("/[ ( (?>[^[]]+) | (?R) )* ]/xis", 
             "",
             "first,second[,b],third[a,b[1,2,3]],fourth[a[1,2]],sixth"
); 

但是下一步卡住了一个

【问题讨论】:

  • 您想使用正则表达式将字符串拆分为字符串数组吗?如果是这样,请将其作为对 get an idea on the regex used 的参考进行检查
  • 我试图删除括号 preg_replace("/[ ( (?>[^[]]+) | (?R) )* ]/xis", "", "first,second[, b],第三[a,b[1,2,3]],第四[a[1,2]],第六");但是在下一步被卡住了
  • 如果你知道你的分隔符是什么样的,你就不需要正则表达式。
  • PHP 有 CSV 解析器。下载一个并使用它。问题解决了。不要用正则表达式这样做(原因很简单:这是浪费时间,因为用正则表达式实际上是不可能的)。

标签: php regex


【解决方案1】:

PHP 的正则表达式支持递归模式,因此可以使用以下方法:

$text = "first,second[,b],third[a,b[1,2,3]],fourth[a[1,2]],sixth";

preg_match_all('/[^,\[\]]+(\[([^\[\]]|(?1))*])?/', $text, $matches);

print_r($matches[0]);

将打印:

数组
(
    [0] => 第一个
    [1] => 秒[,b]
    [2] => 第三[a,b[1,2,3]]
    [3] => 第四[a[1,2]]
    [4] => 第六
)

这里的关键不是split,而是match

你是否想在你的代码库中添加这样一个神秘的正则表达式,取决于你:)

编辑

我刚刚意识到我上面的建议与以[ 开头的条目不匹配。为此,请这样做:

$text = "first,second[,b],third[a,b[1,2,3]],fourth[a[1,2]],sixth,[s,[,e,[,v,],e,],n]";

preg_match_all("/
    (             # start match group 1
      [^,\[\]]    #   any char other than a comma or square bracket
      |           #   OR
      \[          #   an opening square bracket
      (           #   start match group 2
        [^\[\]]   #     any char other than a square bracket
        |         #     OR
        (?R)      #     recursively match the entire pattern
      )*          #   end match group 2, and repeat it zero or more times
      ]           #   an closing square bracket
    )+            # end match group 1, and repeat it once or more times
    /x", 
    $text, 
    $matches
);

print_r($matches[0]);

哪个打印:

数组
(
    [0] => 第一个
    [1] => 秒[,b]
    [2] => 第三[a,b[1,2,3]]
    [3] => 第四[a[1,2]]
    [4] => 第六
    [5] => [s,[,e,[,v,],e,],n]
)

【讨论】:

  • 谢谢!无需解密 - 只需正常工作即可。确实如此)
猜你喜欢
  • 2013-08-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-05
  • 2021-04-01
相关资源
最近更新 更多