tags:

views:

54

answers:

3

I have one string like the following (the number of the {} is unknown):

{test}{test1}{test2}{test3}{test4}

Now I like to get the content in {} out and put them into array. How can I do this? I tried:

preg_match( "/(\{{\S}+\}*/)*")

But the result is wrong. Thanks so much for anyone's help.

+5  A: 
preg_match_all('/{(.*?)}/', $string, $match);
print_r($match[1]);
kemp
+5  A: 
<?php
$string = '{test}{test1}{test2}{test3}{test4}';
$parts = explode('}{', substr($string, 1, -1));

This solution avoids using regular expressions which are often slower than simple string functions. Also, many programmers want to avoid regular expressions whenever practical due to preference.

erisco
+1 for **not** using regular expressions.
zombat
I can't understand why people hate regular expressions so much
kemp
I like regular expressions but I still upvoted this answer :) It just so happens that this is a good solution that doesn't need them (well, except it doesn't validate the input).
Joey Adams
Performance is seldom a valid reason for avoiding regexes. As for preferences, I think @kemp's solution is much clearer than this one.
Alan Moore
You are on the same side of the fence as me then Alan Moore. I knew other responders would provide the regular expression solution, so I decided to provide what the non-regexer's would do.
erisco
Make sure to trim whitespace before and after and between...
drewk
+1  A: 

try preg_match_all('/\{(.+)\}/U', $text)

binaryLV
thanks so much.
kelly