我知道之前有人问过,但这有点不同。
我有一个字符串:
〔脱〕文本1 [FR]文本2 [EN]文本3
我需要拆分键值对,比如
阵列( '去'=> '文本', 'FR'=> '文本', '烯'=> '文本')
我现在这样做,但这不是很优雅(并且在数组的第一个位置产生一个空对象:
$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);
输出:
Array([] => [de] => Text1 [fr] => Text2 [en] => Text3)
答案 0 :(得分:4)
您可以使用preg_match_all()
:
$title = '[de]Text1[fr]Text2[en]Text3';
preg_match_all('~\[([^[]+)\]([^[]+)~', $title, $match);
$output = array_combine($match[1], $match[2]);
您的示例也适用于最小的更改: demo
答案 1 :(得分:1)
尝试使用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);
?>
给你:
Array
(
[de] => Text1
[fr] => Text2
[en] => Text3
)