Extracting Text Enclosed in Square Brackets in PHP
The challenge of capturing text between square brackets in PHP requires a nuanced approach. A common attempt, using /[.*?]/ as a regex, only retrieves the first instance, leaving you with an incomplete result.
Capturing the Enclosure:
To overcome this limitation, utilize regular expressions that encompass the entire text within square brackets. Consider the pattern:
$text = '[This] is a [test] string, [eat] my [shorts].'; preg_match_all("/\[[^\]]*\]/", $text, $matches);
Here, /[1]/ functions as a regex that corresponds to any string enclosed in square brackets. The caret character (^) matches the beginning of the string, followed by a bracket. The 2 portion signifies a character that is not a bracket. The asterisk () matches any number of occurrences, and the trailing bracket concludes the pattern.
Running this regex on the provided text will result in:
Array ( [0] => [This] [1] => [test] [2] => [eat] [3] => [shorts] )
Capturing the Text Inside:
Alternatively, you may wish to extract the text without the brackets. This requires a modified regex:
$text = '[This] is a [test] string, [eat] my [shorts].'; preg_match_all("/\[([^\]]*)\]/", $text, $matches);
In this regex, (3*) captures any character within square brackets, effectively removing the brackets from the output. You will obtain:
Array ( [0] => This [1] => test [2] => eat [3] => shorts )
Remember that this regex assumes square brackets are not nested within the text.
The above is the detailed content of How to Extract Text Enclosed in Square Brackets Using PHP Regular Expressions?. For more information, please follow other related articles on the PHP Chinese website!