Converting a String of Key-Value Pairs into an Associative Array
Problem:
You have a string formatted like "key1value1key2value2key3value3", and you want to convert it into an associative array, where "key1" maps to "value1", "key2" maps to "value2", and so on.
Solution Using Regular Expressions:
The quickest and most straightforward solution involves using a regular expression and array_combine:
preg_match_all("/([^\\]+)\\([^\\]+)/", $string, $p); $array = array_combine($p[1], $p[2]);
This regex identifies adjacent key-value pairs separated by backslashes. The captured groups are then merged into an array using array_combine.
Adapting to Different Delimiters:
This approach can be easily adapted to handle different key-value and pair delimiters. For instance:
# Key/value separated by colons, pair by commas preg_match_all("/([^:]+):([^,]+)/", $string, $p); $array = array_combine($p[1], $p[2]);
Allowing Varying Delimiters:
To permit different delimiters within a single string, a more flexible regex can be used:
preg_match_all("/([^:=]+)[:=]+([^,+&]+)/x", $string, $p);
Other Approaches:
parse_str() with String Replacement:
If the input string already follows the key=value&key2=value2 format, you can use parse_str:
parse_str(strtr($string, ":,", "=&"), $pairs);
Manual Key/Value Separation:
While it's often longer, you can also manually create an array using explode and foreach:
$pairs = array_combine(explode("\", $string, 2, TRUE), explode("\", $string, 2, TRUE));
The above is the detailed content of How Can I Convert a String of Key-Value Pairs into an Associative Array in PHP?. For more information, please follow other related articles on the PHP Chinese website!