Home > Backend Development > PHP Tutorial > How to Extract Multiple Text Segments Enclosed in Square Brackets using PHP?

How to Extract Multiple Text Segments Enclosed in Square Brackets using PHP?

Susan Sarandon
Release: 2024-12-05 07:10:14
Original
982 people have browsed it

How to Extract Multiple Text Segments Enclosed in Square Brackets using PHP?

Capturing Multiple Text Segments Between Square Brackets in PHP

Question:

How to capture all text segments enclosed within square brackets in a given string?

Answer:

To capture multiple text segments between square brackets, use the following regular expression:

/\[[^\]]*\]/
Copy after login

This regex matches any string that begins with a square bracket, contains any number of non-square-bracket characters, and ends with a square bracket.

To extract the captured segments, use the preg_match_all() function. This function takes the regex pattern and the target string as input and returns an array containing all matches. The following PHP code demonstrates how to capture multiple text segments using this regex:

$text = '[This] is a [test] string, [eat] my [shorts].';
preg_match_all("/\[[^\]]*\]/", $text, $matches);
var_dump($matches[0]);
Copy after login

This code produces the following output:

array(4) {
  [0] =>
  string(5) "[This]"
  [1] =>
  string(5) "[test]"
  [2] =>
  string(5) "[eat]"
  [3] =>
  string(7) "[shorts]"
}
Copy after login

Alternative for Extracting Text without Brackets:

To extract only the text within the square brackets, use the following regex:

/\[([^\]]*)\]/
Copy after login

This regex matches any string that begins with a square bracket, contains any number of non-square-bracket characters, and ends with a square bracket. The characters within the brackets are grouped using parentheses.

To extract the captured segments without the square brackets, use the 1 st capture group, as shown in the following PHP code:

preg_match_all("/\[([^\]]*)\]/", $text, $matches);
var_dump($matches[1]);
Copy after login

This code produces the following output:

array(4) {
  [0] =>
  string(4) "This"
  [1] =>
  string(4) "test"
  [2] =>
  string(3) "eat"
  [3] =>
  string(6) "shorts"
}
Copy after login

The above is the detailed content of How to Extract Multiple Text Segments Enclosed in Square Brackets using PHP?. 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