我需要一个函数来返回匹配任何东西的正则表达式和分隔符之间的所有子串。
$str = "{random_one}[SUBSTRING1] blah blah blah {random_two}[SUBSTRING2] blah blah blah{random_one}[SUBSTRING3]";
$resultingArray = getSubstrings($str)
$resultingArray should result in:
array(
[0]: "SUBSTRING1",
[1]: "SUBSTRING2",
[2]: "SUBSTRING3"
)
我一直在搞乱正则表达式而没有运气。任何帮助将不胜感激!
答案 0 :(得分:2)
您可以使用此正则表达式实现此目的:
/{.+?}\[(.+?)\]/i
<强>详情
{.+?} # anything between curly brackets, one or more times, ungreedily
\[ # a bracket, literally
(.+?) # anything one or more times, ungreedily. This is your capturing group - what you're after
\] # close bracket, literally
i # flag for case insensitivity
在PHP中它看起来像这样:
<?php
$string = "{random_one}[SUBSTRING1] blah [SUBSTRINGX] blah blah {random_two}[SUBSTRING2] blah blah blah{random_one}[SUBSTRING3]";
preg_match_all("/{.+?}\[(.+?)\]/i", $string, $matches);
var_dump($matches[1]);