Reputation: 3758
I have values that look like this...
{X}{Y}{Z}{R}{R}
I have 2 questions, first question, how can I explode it so the resulting array looks like this...
Array
(
[0] => {X}
[1] => {Y}
[2] => {Z}
[3] => {R}
[4] => {R}
)
And the second question is, how can I explode it like this...
Array
(
[0] => X
[1] => Y
[2] => Z
[3] => R
[4] => R
)
Upvotes: 1
Views: 1404
Reputation: 95101
All you need is :
$str = "{X}{Y}{Z}{R}{R}" ;
preg_match_all("/\{([A-Z])\}/", $str,$matches);
print_r($matches);
Array
(
[0] => Array
(
[0] => {X}
[1] => {Y}
[2] => {Z}
[3] => {R}
[4] => {R}
)
[1] => Array
(
[0] => X
[1] => Y
[2] => Z
[3] => R
[4] => R
)
)
This uses the regular expression \{([A-Z])\}
. Bit-by-bit, it means:
\{
Match a literal {
.(...)
Match the content within normally, but capture whatever text it matched.
[A-Z]
Match any character between A
and Z
.\}
Match a literal }
.We use preg_match_all
to find all instances of this pattern. Group 0 is the entire match (including the braces), and group 1 contains only the data captured using the parentheses.
Upvotes: 5