在圆括号和方括号之间捕获

时间:2017-07-09 12:40:24

标签: php regex

我的文字类似于:

[text]
(more text)
(text...)
[text!]
(last text)

我需要匹配()和[]之间的文本 输出应该是这样的:

[
  "text",
  "more text",
  "text...",
  "text!",
  "last text"
]

我已经尝试/[\[\(](.*?)[\]\)]/,但它在PHP中没有用 如果需要,可以使用以下代码:

 preg_match_all('/[\[\(](.*?)[\]\)]/', $text, $matches, PREG_SET_ORDER, 0);
 var_dump($matches);

如何在PHP中使用正则表达式实现此目的?

提前致谢,
Skayo

2 个答案:

答案 0 :(得分:2)

实际上,该代码就像魅力一样。您只需添加一行来过滤掉匹配的部分:

$texts = array_column($matches, 1);

有关工作示例,请参阅https://3v4l.org/uCHIB

答案 1 :(得分:2)

我建议使用基于branch reset功能的正则表达式:

$re = '/(?|\[([^]]*)]|\(([^)]*)\))/';
$str = '[text]
(more text)
(text...)
[text!]
(last text)';

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

请参阅PHP demo

请参阅regex demo

  • (?| - 启动分支重置
  • \[ - [
  • ([^]]*) - 除]
  • 以外的任何0 +字符
  • ] - 文字]
  • | - 或
  • \( - 文字(
  • ([^)]*) - 除)
  • 以外的任何0 +字符
  • \) - 文字)
  • ) - 分支重置组的结尾。