0

i'm looking for a way to get a text with regex that lies between 2 open and closing square brackets. As an example:

$text = "[[ Hello I like trains ] [ I'm hungry ]]
             [[ I smell good ] [ I use stackoverflow ]]" 

// Thats one string, the break is just so it's easier to see, that there are two "[[...]]" sentences

What I need right now is a array as a result that looks like that:

$array = [
    0 => "[Hello I like trains] [I'm hungry]",
    1 => "[I smell good] [I use stackoverflow]"
];

What I tried is that:

if (preg_match_all('\[\[(.*?)\]\]', $text, $matches)) {
      dd($matches);
} else return "hello";

What I get:

preg_match_all(): Delimiter must not be alphanumeric or backslash

To be honest, i'm not really familiar with regex.

I just want the regex to cut out the text, which is between "[[" "]]". But the first "[" and the last "]" of the double square brackets, need's to be there in the result and should not be removed.

so

"[[ Hello I like trains ] [ I'm hungry ]]"

will be

"[ Hello I like trains ] [ I'm hungry ]"

at the end.

If there are more "[[" "]]" sentences, the regex shall put it in a array. Like in my example result array above.

I'm working with PHP/Laravel 5.6

1 Answers1

1

You need something like this

if (preg_match_all('/\[(\[(.*?)\])\]/is', $text, $matches)) {
  print_r($matches[1]);
} else return "hello";
Rinsad Ahmed
  • 1,777
  • 1
  • 4
  • 19