Home > Backend Development > PHP Tutorial > How to Extract Text Enclosed in Square Brackets Using PHP Regular Expressions?

How to Extract Text Enclosed in Square Brackets Using PHP Regular Expressions?

Mary-Kate Olsen
Release: 2024-11-28 15:57:10
Original
1033 people have browsed it

How to Extract Text Enclosed in Square Brackets Using PHP Regular Expressions?

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);
Copy after login

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]
)
Copy after login

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);
Copy after login

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
)
Copy after login

Remember that this regex assumes square brackets are not nested within the text.


  1. ]
  2. ]
  3. ]

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template