zak_mckraken
zak_mckraken

Reputation: 805

Split a string while keeping delimiters and string outside

I'm trying to do something that must be really simple, but I'm fairly new to PHP and I'm struggling with this one. What I want is to split a string containing 0, 1 or more delimiters (braces), while keeping the delimiters AND the string between AND the string outside.

ex: 'Hello {F}{N}, how are you?' would output :

Array ( [0] => Hello 
        [1] => {F}
        [2] => {N} 
        [3] => , how are you? ) 

Here's my code so far:

$value = 'Hello {F}{N}, how are you?';
$array= preg_split('/[\{\}]/', $value,-1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
print_r($array);

which outputs (missing braces) :

Array ( [0] => Hello 
        [1] => F
        [2] => N 
        [3] => , how are you? )

I also tried :

preg_match_all('/\{[^}]+\}/', $myValue, $array);

Which outputs (braces are there, but the text outside is flushed) :

Array ( [0] => {F} 
        [1] => {N} ) 

I'm pretty sure I'm on the good track with preg_split, but with the wrong regex. Can anyone help me with this? Or tell me if I'm way off?

Upvotes: 1

Views: 228

Answers (2)

PleaseStand
PleaseStand

Reputation: 32052

You need parentheses around the part of the expression to be captured:

preg_split('/(\{[^}]+\})/', $myValue, -1, PREG_SPLIT_DELIM_CAPTURE);

See the documentation for preg_split().

Upvotes: 0

Blender
Blender

Reputation: 298106

You aren't capturing the delimiters. Add them to a capturing group:

/(\{.*?\})/

Upvotes: 1

Related Questions