1

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.

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.

Rizier123
  • 58,877
  • 16
  • 101
  • 156
Scott P
  • 835
  • 7
  • 12

2 Answers2

1

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"]);
Rizier123
  • 58,877
  • 16
  • 101
  • 156
1

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];
}
michael.schuett
  • 4,248
  • 4
  • 28
  • 39