tags:

views:

149

answers:

3

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  A: 

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.
cletus
What is the wrapping for?
Joseph Carrington
@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.
Alix Axel
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 ~).
cletus
+1  A: 
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.

Alan Moore
Why are there double quotes and then single quotes surrounding the expression?
Joseph Carrington
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.
Alan Moore
A: 

Try preg_split()

Ben Rowe
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.)
Alan Moore