43

I need some way of capturing the text between square brackets. So for example, the following string:

[This] is a [test] string, [eat] my [shorts].

Could be used to create the following array:

Array ( 
     [0] => [This] 
     [1] => [test] 
     [2] => [eat] 
     [3] => [shorts] 
)

I have the following regex, /\[.*?\]/ but it only captures the first instance, so:

Array ( [0] => [This] )

How can I get the output I need? Note that the square brackets are NEVER nested, so that's not a concern.

Giacomo1968
  • 25,759
  • 11
  • 71
  • 103
Chuck Le Butt
  • 47,570
  • 62
  • 203
  • 289

1 Answers1

115

Matches all strings with brackets:

$text = '[This] is a [test] string, [eat] my [shorts].';
preg_match_all("/\[[^\]]*\]/", $text, $matches);
var_dump($matches[0]);

If You want strings without brackets:

$text = '[This] is a [test] string, [eat] my [shorts].';
preg_match_all("/\[([^\]]*)\]/", $text, $matches);
var_dump($matches[1]);

Alternative, slower version of matching without brackets (using "*" instead of "[^]"):

$text = '[This] is a [test] string, [eat] my [shorts].';
preg_match_all("/\[(.*?)\]/", $text, $matches);
var_dump($matches[1]);
Naki
  • 1,616
  • 1
  • 15
  • 17