Capturing text between square brackets in PHP

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

Leave a Comment