Parsing Key-Value Expressions from Comma-Separated Strings
Converting a comma-separated string of key-value expressions into an associative array is a common task in PHP. A simple approach might involve exploding the string into an array, trimming each element, and then separating each element into key and value using another explosion. However, there's a more efficient way to accomplish this using regular expressions.
Given a string like "key=value, key2=value2," here's how you can parse it with regex:
$str = "key=value, key2=value2"; preg_match_all("/([^,= ]+)=([^,= ]+)/", $str, $r); $result = array_combine($r[1], $r[2]); var_dump($result);
The regex pattern /([^,= ] )=([^,= ] )/ matches any sequence of non-space, non-comma, and non-equal characters followed by an equal sign (=), followed by another sequence of non-space, non-comma, and non-equal characters. The preg_match_all function is then used to match the pattern in the string and capture the matched groups in an array ($r). Finally, the array_combine function is used to merge the first and second captured groups ($r[1] and $r[2]) as the keys and values of the associative array.
This approach efficiently parses key-value expressions in a single regular expression match, without the need for multiple array transformations or loops. The result is a neatly constructed associative array where each key maps to its respective value.
The above is the detailed content of How to Efficiently Parse Key-Value Pairs from a Comma-Separated String in PHP?. For more information, please follow other related articles on the PHP Chinese website!