1

I need to create an array by searching a string for occurrences of '[' followed by 0 or more characters followed by ']'.

My test string:

$string="[item 1] [2] [] [item3]";

All of the above must be matched.

I think the regex to do so is

\[*\]

But how do I create an array out of the string? Do I use

preg_match_all("\[*\]", $string, $matches);

?

1
  • FYI, "split" isn't the right word for what you're doing; check out the docs for preg_split() to see what it does. This is the inverse of a split. Commented Aug 21, 2009 at 3:17

3 Answers 3

2
preg_match_all('/\[.*?\]/', $string, $matches);

or

preg_match_all('/\[[^\[\]]*\]/', $string, $matches);

The first one stops matching as soon as it sees a closing bracket, but it will match an opening bracket if it sees one first. That is, it would match "[ [foo]" if it's present in the input.

The second one is more robust because will only find properly balanced square brackets; ie, they can't contain square brackets. If brackets can be nested, neither regex will work; that's a much more complicated problem.

Sign up to request clarification or add additional context in comments.

2 Comments

Why are there double quotes and then single quotes surrounding the expression?
That was a typo; I was replacing the doubles with singles but I got distracted. In general, you should prefer single quotes so you don't have to worry about escaping backslashes. Of course, if you're taking advantage of variable interpolation, you have to use double quotes.
1

Close:

preg_match_all("!\[.*?\]!", $string, $matches);

and then $matches[0] will contain the strings.

Three changes were made:

  1. Wrapped expression in ! (you can use / or whatever);
  2. It's .* not * (in your example [* is saying "0 or more ["); and
  3. It was made non-greedy with .*?. If you don't then you will get only one match containing basically the whole string. Take a look at Finer points of PHP regular expressions.

2 Comments

@Joseph: It's called the delimiter, normally it's \ but you may want to use something that's not regulary in the subject string, otherwise you'll have to escape it. For me, ~ works.
Yes I generally use ! instead of / because / often appears in the search pattern (or at least it does for me) but ! rarely does. Others use different things (eg eyze uses ~).
0

Try preg_split()

1 Comment

Why do you think preg_split() would work better than preg_match_all()? (It's a trick question; ignore the title and read the question again.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.