PHP在键值对中拆分字符串 [英] PHP Split string in key value pairs
本文介绍了PHP在键值对中拆分字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道之前已经问过这个问题,但这有点不同。
I know this has been asked before but this is a bit different.
我有一个字符串,例如:
I have a string like:
[de] Text1 [fr] Text2 [en] Text3
[de]Text1[fr]Text2[en]Text3
array('de'=>'Text','fr'=>'Text','en '=>'文本')
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);
输出:
Array([] => [de] => Text1 [fr] => Text2 [en] => Text3)
Array ( [] => [de] => Text1 [fr] => Text2 [en] => Text3 )
推荐答案
您可以使用 preg_match_all()
:
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]);
您的示例也将进行最小的更改: < a href = https://eval.in/313117 rel = nofollow>演示
这篇关于PHP在键值对中拆分字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文