PHP Split string in key value pairs

浪尽此生 提交于 2019-12-11 10:37:20

问题


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 )


回答1:


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




回答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
)


来源:https://stackoverflow.com/questions/29620231/php-split-string-in-key-value-pairs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!