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.
Extract Text Between Parenthesis To extract the text between any characters, use a formula with the MID and FIND functions. The FIND Function locates the parenthesis and the MID Function returns the characters in between them.
You can omit the first backslash. [[\]] will match either bracket. In some regex dialects (e.g. grep) you can omit the backslash before the ] if you place it immediately after the [ (because an empty character class would never be useful): [][] .
In PHP, elements can be added to the end of an array by attaching square brackets ([]) at the end of the array's name, followed by typing the assignment operator (=), and then finally by typing the element to be added to the array. Ordered Arrays.
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]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With