将键/值字符串转换为关联数组 [英] Convert key/value string into associative array
问题描述
例如,我的字符串可能如下所示:
As an example, my string might look like this:
first_name:Tom last_name:Jones email:tom@somedomain.com
我希望我的数组如下所示:
I would want my array to look like the following:
Array (
['first_name'] => 'Tom',
['last_name'] => 'Jones',
['email'] => 'tom@somedomain.com'
)
然后将根据列和值将其用于搜索数据库.因此,我首先需要检索键(例如first_name)和值(例如Tom)以进行搜索.
This will then be used to search the database based on the column and value. So I will first need to retrieve the key (such as first_name) and the value (like Tom) for searching.
我有以下正则表达式:
((?:[a-z][a-z0-9_]*))
这有效.它会找到:
之前和:
之后的所有字符串,但是我无法弄清楚如何解析它以将其放入所需格式的数组中.
This works. It finds all strings before :
and after :
, but I cannot figure out how to parse this to put it in an array of the format I need.
推荐答案
您可以先在一个空格上先 explode()
您的字符串,然后分别使用 array_map()
冒号的价值.之后,只需使用 array_column()
将键和值放置到位:
You can just explode()
your string first on a space and then with array_map()
each value on a colon. After that just use array_column()
to get the keys and values into place:
$result = array_column(array_map(function($v){
return explode(":", $v);
}, explode(" ", $str)), 1, 0);
您还可以在开始时使用正则表达式来完成此操作,并使用命名的捕获组,例如
You can also do it with a regex as you started and use named capturing groups, e.g.
preg_match_all("/(?P<keys>\w+):(?P<values>[\w@]+)/", $str, $m);
$result = array_combine($m["keys"], $m["values"]);
这篇关于将键/值字符串转换为关联数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!