2

I know this has been asked before but this is a bit different.

I have a string like:

[de]Text1[fr]Text2[en]Text3

that I need to split in key-value pairs like

array('de'=>'Text','fr'=>'Text','en'=>'Text')

I do it like this at the moment, but this is not very elegant (and produces an empty object at the first place in the array:

$title = '[de]Text1[fr]Text2[en]Text3';

$titleParts = explode('[',$title);

$langParts;
foreach($titleParts as $titlePart){
    $langPart = explode(']',$titlePart);
    $langParts[$langPart[0]] = $langPart[1];
}

print_r($langParts);

Output:

Array ( [] => [de] => Text1 [fr] => Text2 [en] => Text3 )

3
  • What are you actually trying to do ? Commented Apr 14, 2015 at 6:13
  • As written, I need to split a string (given above) into key-value pairs (given above) as per my code (given above) but more elegant. But thanks for the downvote anyway... Commented Apr 14, 2015 at 6:15
  • Why not make an Json array? Commented Apr 14, 2015 at 6:15

2 Answers 2

4

You could use preg_match_all():

$title = '[de]Text1[fr]Text2[en]Text3';
preg_match_all('~\[([^[]+)\]([^[]+)~', $title, $match);
$output = array_combine($match[1], $match[2]);

demo

Your example will also work with minimal change: demo

Sign up to request clarification or add additional context in comments.

4 Comments

Ah, we did same preg_match_all(). I'll delete mine
@Rasclatt: you didn't need to do that, your pattern was different, and the loop also, so the answer is different...
Yeah, approach is the same though, I'll undelete it, but I don't know that my preg_match expression is as good as yours.
And your array_combine() is genius. Yours is better all around! Nice.
2

Try using a preg_match_all():

<?php
    $title = '[de]Text1[fr]Text2[en]Text3';
    preg_match_all('/([\[a-z\]]{1,})([a-zA-Z0-9]{1,})/',$title,$match);

    if(isset($match[2])) {
            foreach($match[1] as $key => $value) {
                    $array[str_replace(array("[","]"),"",$value)] = $match[2][$key];
                }
        }
    print_r($array);
?>

Gives you:

Array
(
    [de] => Text1
    [fr] => Text2
    [en] => Text3
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.