我有一个像下面这样的字符串。
"|dm:12|em:.25|fm:10|wm:85|de:143|qty:1"
如何将其转换为键值对?
答案 0 :(得分:1)
好吧,我很无聊。只需将 |
替换为 &
并将 :
替换为 =
以获取要解析为数组的查询字符串:
parse_str(str_replace(['|', ':'], ['&', '='], $string), $result);
或者你可以捕捉你想要的片段并将它们组合起来:
preg_match_all('/\|([^:]+):([^|]+)/', $string, $matches);
$result = array_combine($matches[1], $matches[2]);
|
([^:]+)
匹配并捕获任何非 :
:
([^|]+)
匹配并捕获任何非 |