简体   繁体   English

将键/值字符串转换为关联数组

[英]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'
)

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. 所以我首先需要检索密钥(例如first_name)和值(如Tom)进行搜索。

I have the following regex: 我有以下正则表达式:

((?:[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. 它发现的所有字符串前:: ,但我无法弄清楚如何解析这个把它放在我需要的格式的数组。

The above method works but is overly hard to read in my opinion. 上述方法有效但在我看来过于难以阅读。 You can much more easily and efficiently do this with the following method no need to make three extra function calls. 您可以使用以下方法更轻松有效地执行此操作,无需进行三次额外的函数调用。

$user_info = 'first_name:Tom last_name:Jones email:tom@somedomain.com';

$user = array();
foreach (explode(' ', $user_info) as $property) {
    $part = explode(':', $property);
    $user[$part[0]] = $part[1];
}

You can just explode() your string first on a space and then with array_map() each value on a colon. 你可以先在空格上explode()你的字符串,然后使用array_map()冒号上的每个值。 After that just use array_column() to get the keys and values into place: 之后,只需使用array_column()将键和值放置到位:

$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, eg 您也可以在开始时使用正则表达式并使用命名捕获组,例如

preg_match_all("/(?P<keys>\w+):(?P<values>[\w@]+)/", $str, $m);
$result = array_combine($m["keys"], $m["values"]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM