M
M
mountain1232015-01-02 11:11:22
PHP
mountain123, 2015-01-02 11:11:22

How to select text between multiple square brackets using regular expressions?

for example, there is a text "apple [green] apple and also red"
using the regular expression /\[(.+)\]/ I pull out everything between square brackets, that is, the word "green",
But if the text is like this - "apple [green] apple and [still] red", then the "green] apple and [still"
what regular expression is needed to get both or more words in square brackets?

$subject = "яблоко красное и [зеленое] яблоко и еще [одно] красное яблоко и [еще] одно яблоко, зеленое";
$pattern = '/\[(.+)\]/';
preg_match($pattern, substr($subject,3), $matches, PREG_OFFSET_CAPTURE);
print_r($matches);

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey Ukolov, 2015-01-02
@mountain123

$subject = "яблоко красное и [зеленое] яблоко и еще [одно] красное яблоко и [еще] одно яблоко, зеленое";
$pattern = '/\[(.+?)\]/';
preg_match_all($pattern, substr($subject,3), $matches);
print_r($matches);

First, you need to use a lazy quantifier - add a question mark after the ".+". Thus, the search will be performed until the first match, and not until the last.
Second, you need to use preg_match_all if you want all matches.

A
abs0lut, 2015-01-02
@abs0lut

Here's another option:
\[([^\[\]]+)\]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question