2017-09-20 52 views
1

我需要一个函数,它返回匹配任何东西的正则表达式和分隔符之间的所有子串。PHP - 查找两个正则表达式之间的子串

$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

这有点不清楚。你需要括号内的所有内容吗?尝试[this](https://3v4l.org/GS7YP)。 – ishegg

+0

@ishegg yes在{anything} [this_is_what_i_need]之后括号内的所有内容 - 我会检查出 – hunijkah

+1

哦,如果之前需要在卷曲之间存在字符串,请尝试[this instead](https://3v4l.org/ gmh9q)。这些比赛在'$匹配[1]' – ishegg

回答

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]); 

Demo

+0

这正是我所需要的,非常感谢! – hunijkah

+0

这没有问题。祝你好运! – ishegg

相关问题