Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capturing text between square brackets in PHP

Tags:

string

regex

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.

like image 825
Chuck Le Butt Avatar asked Apr 11 '12 10:04

Chuck Le Butt


People also ask

How do you put text in between brackets?

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.

How do you match square brackets in regex?

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): [][] .

What do square brackets mean in PHP?

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.


1 Answers

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]); 
like image 114
Naki Avatar answered Oct 05 '22 07:10

Naki