Convert Backslash-Delimited String into an Associative Array
In PHP, a common task is to process strings formatted with key-value pairs separated by a separator. A common example is a backslash-delimited string, where key and value pairs are separated by a backslash ().
Using preg_match_all and array_combine
One effective method involves using the preg_match_all function to extract both keys and values into separate arrays, which are then combined using array_combine.
preg_match_all("/([^\\]+)\\([^\\]+)/", $string, $p); $array = array_combine($p[1], $p[2]);
This regex pattern matches any non-backslash characters into $p[1] (keys) and any non-backslash characters into $p[2] (values).
Customizing Key/Value Separators
This approach can be generalized to handle different key-value separators:
preg_match_all("/ ([^:]+) : ([^,]+) /x", $string, $p); $array = array_combine($p[1], $p[2]);
Simply replace ":" with your desired key-value separator and "," with your desired pair delimiter.
Allowing Varying Delimiters
To allow varying delimiters, use:
preg_match_all("/ ([^:=]+) [:=]+ ([^,+&]+) /x", $string, $p);
This permits key=value, key2:value2, or similar variations.
Additional Features
You can further enhance the extraction:
Alternative: parse_str
For convenient handling of key=value&key2=value2 strings, consider using parse_str with strtr:
parse_str(strtr($string, ":,", "=&"), $pairs);
Considerations
Choose the most appropriate method based on your requirements and trade-offs.
The above is the detailed content of How can I convert a backslash-delimited string into an associative array in PHP?. For more information, please follow other related articles on the PHP Chinese website!