PHP - 在两个正则表达式之间查找子字符串

时间:2022-11-27 18:41:38

I need a function that returns all substrings between a regex expression that matches anything and a delimiter.

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

$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"
)

I've been messing with regex with no luck. Any help would be greatly appreciated!

我一直在搞乱正则表达式而没有运气。任何帮助将不胜感激!

1 个解决方案

#1


2  

You can achieve that with this regular expression:

您可以使用此正则表达式实现此目的:

/{.+?}\[(.+?)\]/i

Details

{.+?}   # 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

In PHP it would look like this:

在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

#1


2  

You can achieve that with this regular expression:

您可以使用此正则表达式实现此目的:

/{.+?}\[(.+?)\]/i

Details

{.+?}   # 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

In PHP it would look like this:

在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