Elitmiar
Elitmiar

Reputation: 36889

Parse string containing curly-brace-styled opening and closing tags

I have the following string

{item1}home::::Home{/item1}{item2}contact_us::::Contact Us{/item2}{item3}.....

and so it goes on.

I need to split the string the following way.

[
    '{item1}home::::Home{/item1}',
    '{item2}contact_us::::Contact Us{/item2}',
    ...
]

Upvotes: 0

Views: 82

Answers (3)

slikts
slikts

Reputation: 8158

You could do it like this:

$text = "{item1}home::::Home{/item1}{item2}contact_us::::Contact Us{/item2}{item3}.....){/item3}";
preg_match_all('/{item\d}.+?{\/item\d}/', $text, $results);

var_dump($results) would produce:

Array
(
    [0] => Array
        (
            [0] => {item1}home::::Home{/item1}
            [1] => {item2}contact_us::::Contact Us{/item2}
            [2] => {item3}.....){/item3}
        )

)

Upvotes: 3

RaYell
RaYell

Reputation: 70484

$input = '{item1}home::::Home{/item1}{item2}contact_us::::Contact Us{/item2}{item3}.....';
$regex = '/{(\w+)}.*{\/\1}/';
preg_match_all($regex, $input, $matches);
print_r($matches[0]);

Upvotes: 4

Stephen Doyle
Stephen Doyle

Reputation: 3744

Use preg_split() with the regex pattern /{.*?}.*?{\/.*?}/

Upvotes: 2

Related Questions