我需要使用正则表达式匹配[[ and ]]之间的任何内容。然后我需要将在括号之间找到的所有值放入一个数组中。
示例文本:
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]]]但不是最后一个,因为它最后只有两个[。
发布于 2012-09-10 21:57:30
这将检查以下内容:
[[[]-or-
] not that that or-
]not that
后跟]]]的是
preg_match_all('/\[\[\[(?:(?:[^\]]*|]{1,2}(?!]))*)]]]/', $string, $matches);
print_r($matches[0]);这种正则表达式的好处是可以在三方括号包装器(例如[[[foo]bar]]] )中匹配]。
注意: ]不需要进行转义,但在字符类内部除外。
发布于 2012-09-10 22:26:34
一般的解决方案是这样的:
\[{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)当长输入字符串中没有"]]]"时,积极的先行检查是一个安全的子句,允许表达式快速失败。
一旦确定"]]]"将在字符串前面的某个点跟随,负前视确保表达式正确匹配字符串,如下所示:
[[[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-10 21:46:46
更安全的解决方案:
\[{3}[^\]]+?\]{3}https://stackoverflow.com/questions/12352977
复制相似问题