1

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!

5
  • It's a bit unclear. You need everything between the brackets? Try this. Commented Sep 20, 2017 at 1:43
  • @ishegg yes everything between the brackets after {anything}[ this_is_what_i_need ] - i'll check that out Commented Sep 20, 2017 at 1:44
  • 1
    Oh, if there needs to be a string between curly before, try this instead. The matches are in $matches[1] Commented Sep 20, 2017 at 1:45
  • @ishegg $matches[1] is near perfect! Do you know how to remove the brackets from it though?? Commented Sep 20, 2017 at 1:49
  • 1
    Leave them out of the capturing group - I'll write an answer, just a second. Commented Sep 20, 2017 at 1:50

1 Answer 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
$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

Sign up to request clarification or add additional context in comments.

2 Comments

This is exactly what I needed, Thank you so much!
It's no problem. Good luck!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.