3

我需要使用正则表达式匹配 [[[ 和 ]]] 之间的任何内容。然后我需要将括号之间的所有值放入一个数组中。

示例文本:

here is some 'test text [[[media-2 large right]]], [[[image-0 large left]]] the another token [[[image-1]]

从上面的文本我需要匹配前两个:

1, [[[media-2 large right]]]
2, [[[image-0 large left]]]

但不是最后一个,因为它最后只有两个 [。

4

5 回答 5

2

这将检查:

  1. [[[
  2. 其次是:
    1. 除了] - 或 -
    2. 一到二]不跟]
  3. 其次是]]]
preg_match_all('/\[\[\[(?:(?:[^\]]*|]{1,2}(?!]))*)]]]/', $string, $matches);
print_r($matches[0]);

此正则表达式具有匹配]三方括号包装器内部的好处(例如[[[foo]bar]]].

注意: ]不需要转义,除了在字符类中。

于 2012-09-10T13:57:30.413 回答
2

一个通用的解决方案是这个:

\[{3}(?=.*?\]{3}(?!\]))((?:(?!\]{3}(?!\])).)*)

它读到

\[{3}         # 3 opening square brackets
(?=           # begin positive look-ahead ("followed by..."
  .*?\]{3}    #   ...3 closing brackets, anywhere ahead (*see explanation below)
  (?!\])      #   negative look-ahead: no more ] after the 3rd one
)             # end positive look-ahead
(             # begin group 1
  (?:         #   begin non-matching group (for atomic grouping)
    (?!       #     begin negative look-ahead ("not followed by"):
      \]{3}   #       ...3 closing square brackets
      (?!\])  #       negative look-ahead: no more ] after the 3rd one
    )         #     end negative look-ahead
    .         #     the next character is valid, match it
  )           #   end non-matching group
)             # end group 1 (will contain the wanted substring)

正向前瞻是一个保障条款,它允许表达式"]]]"在长输入字符串中没有任何内容时快速失败。

一旦确定 a"]]]" 在字符串前面的某个点跟随,否定的前瞻确保表达式正确匹配这样的字符串:

[[[foo [some text] bar]]]
                 ^
                 +-------- most of the other solutions would stop at this point

此表达式检查每个字符是否]跟随三个,因此在此示例中它将包括" bar".

表达式的"no more ] after the 3rd one"一部分确保匹配不会过早结束,因此在这种情况下:

[[[foo [some text]]]]

比赛还是会"foo [some text]"
没有它,表达式会过早停止 ( "foo bar [some text")。

副作用是我们不需要实际匹配"]]]",因为积极的前瞻清楚地表明它们在那里。我们只需要匹配它们,负前瞻就可以很好地做到这一点。

请注意,如果您的输入包含换行符,您需要在“dotall”模式下运行表达式。

另见:http ://rubular.com/r/QFo9jHEh9d

于 2012-09-10T14:26:34.023 回答
1

更安全的解决方案:

\[{3}[^\]]+?\]{3}
于 2012-09-10T13:46:46.180 回答
0

我认为这有效:

\[\[\[(.*)\]\]\]

但这可能是新的方法:)

于 2012-09-10T13:44:26.197 回答
0

如果您的字符串将始终遵循该格式,subject, size, position,您可以使用:

$string = "here is some 'test text [[[media-2 right]]], [[[image-0]]] the another [[[image-1 left large]]] and token [[[image-1]]";

preg_match_all('/[\[]{3}(.*?)(.*?)?(.*?)?[\]]{3}/', $string, $matches);
print_r($matches);
于 2012-09-10T13:48:22.370 回答