Capturing text between square brackets in PHP

Capturing text between square brackets in PHP

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Capturing Text Between Square Brackets in PHP

The regex pattern /\[.*?\]/ fails to capture multiple instances because of how the dot operator (.) behaves by default in PHP's PCRE engine. The . matches any character except a newline, but it is greedy unless explicitly modified. While you have correctly used the non-greedy quantifier *?, which tells the engine to match as few characters as possible initially, the surrounding context often dictates the actual behavior.

In your specific example, the issue isn't necessarily that the pattern stops after the first match; it is likely a matter of how the result is being retrieved or if the regex flags are preventing global matching. To extract all occurrences of text between square brackets from a string like [This] is a [test] string, you need to ensure your regular expression finds every non-overlapping match within the input.

The core pattern remains robust: /\[.*?\]/. This looks for an opening bracket, captures any number of characters (non-greedy) until it hits the first closing bracket, and then stops. To get all results, you must use the global flag (g). Without this flag, the regex engine processes the string once and returns only the first match found.

Here is how to implement this correctly in PHP using preg_match_all:

<?php
$string = "[This] is a [test] string, [eat] my [shorts].";
$pattern = '/\[.*?\]/';

// The 'g' flag is essential here to find all matches
if (preg_match_all($pattern, $string, $matches)) {
    print_r($matches[0]);
}

This approach returns an array containing every instance of the bracketed text. If you prefer not to use the global flag with preg_match_all, you can use preg_split or a simple preg_match loop, but preg_match_all is the most efficient and readable solution for this specific extraction task.

Handling Nested Brackets

Your source material explicitly notes that square brackets are never nested, which simplifies the problem significantly. If nesting were allowed (e.g., [outer [inner] text]), a standard regex like /\[.*?\]/ would fail because the non-greedy quantifier would close at the first ], yielding [outer [ and leaving the rest unmatched. In such scenarios, you would need to abandon pure regular expressions in favor of a parser or a more complex recursive pattern, though those solutions are often overkill for simple extraction tasks.

Since nesting is ruled out, your regex does not need to account for balance or depth. It can rely strictly on the first closing bracket encountered after an opening one. This constraint makes the .*? quantifier safe and predictable.

Performance and Readability Considerations

Using preg_match_all with the global flag is generally preferred over looping through preg_match repeatedly. The former compiles the pattern once and scans the string in a single pass, returning all matches in one operation. This reduces CPU overhead compared to calling the matching function multiple times, especially on large datasets.

While PHP offers several libraries for parsing text, such as using a StreamWrapper or writing a custom tokenizer, regular expressions remain the standard tool for pattern extraction unless the pattern becomes extremely complex. For extracting bracketed content, regex is concise and performant enough for almost all use cases involving flat text data.

If you are working within a Laravel application, you might find utility in packages that extend string manipulation capabilities, but native PHP functions are sufficient here. The logic of capturing delimited sections is fundamental to many text-processing tasks, from parsing log files to extracting configuration values from INI-style strings.

Our network