将以下字符串拆分为键值数组的最佳方法是什么
$string = 'FullName=Thomas Marquez,Address=1234 Sample Rd, Apt 21, XX 33178,Age=37,Code=123';
预期输出
Array
(
[FullName] => Thomas Marquez
[Address] => 1234 Sample Rd, Apt 21, XX 33178
[Age] => 37
[Code] => 123
)
最佳答案
您可以将 preg_match_all()
与此正则表达式一起使用:
/([a-z]+)=([^=]+)(,|$)/i
详情
/
([a-z]+) match any letter 1 or more times (you can change it to \w if you need numbers
= match a literal equal sign
([^=]+) match anything but an equal sign, 1 or more times
(,|$) match either a comma or the end of the string
/i case-insensitive flag
像这样:
<?php
$string = "FullName=Thomas Marquez,Address=1234 Sample Rd, Apt 21, XX 33178,Age=37,Code=123";
preg_match_all("/([a-z]+)=([^=]+)(,|$)/i", $string, $m);
var_dump($m[1]); // keys
var_dump($m[2]); // values
var_dump(array_combine($m[1], $m[2])); // combined into one array as keys and values
关于php - 在 PHP 中用等号和逗号分割字符串的最佳方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46010236/