php 正则表达式方括号和逗号

php regex square brackets and commas

我想捕获下面字符串中方括号和逗号内的文本。

$_['text_1']      = 'text_2 %d to %d of %d (%d text)';

我有方括号的正则表达式

preg_match_all("/\[[^\]]*\]/",$string,$matches); //all strings with brackets

需要两个正则表达式
  1. text_1
  2. text_2 %d 到 %d,共 %d 个(%d 文本)

你的 "/\[[^\]]*\]/" 只匹配 [.[.[..].

这样的子字符串

您可以使用

轻松获取值
(?|\['([^][]*)']|'([^'\]*(?:\.[^'\]*)*)')

参见 regex demo,您的值将在第 1 组中。

PHP demo:

$re = "/(?|\['([^][]*)']|'([^'\\]*(?:\\.[^'\\])*)')/"; 
$str = "$_['text_1']      = 'text_2 %d to %d of %d (%d text)';"; 
preg_match_all($re, $str, $matches);
print_r($matches[1]);

由于使用了分支重置分组 (?|..|..),正则表达式包含 2 个备选方案和 2 个具有索引 1 的捕获组。 2 个备选方案匹配:

  • \['([^][]*)'] - 文字 [',后跟 ][ 以外的 0 个或多个字符,直到 ']
  • '([^'\]*(?:\.[^'\]*)*)') - 单引号内可能包含任何转义序列的任何子字符串。

或者更安全的方法,它也允许第一组中的任何 [](即,如果你有 $_['P[O]ST'],但我认为这不太可能):

(?|\['([^']*(?:'(?!])[^']*)*)'\]|'([^'\]*(?:\.[^'\]*)*)')

another demo