问题
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