Chuck Le Butt
Chuck Le Butt

Reputation: 48826

Capturing text between square brackets in PHP

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.

Upvotes: 44

Views: 78033

Answers (1)

Naki
Naki

Reputation: 1636

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

Upvotes: 117

Related Questions