php - 在 PHP 中用等号和逗号分割字符串的最佳方法是什么

标签 php regex string

将以下字符串拆分为键值数组的最佳方法是什么

$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/

相关文章:

php - 用于查找 URL 的正则表达式,可以改进吗?

Java String的split方法忽略空子串

php - 带参数的 laravel ajax 操作 url

php - 统计返回的记录 MySQL Doctrine

javascript - 如何编写一个表示 if ' string starts with BT ' 的正则表达式?

正则表达式在 MongoDB 中说不是这个字符

php - 如何在单个 session 期间更改数据库

php - 适用于 PHP 和 Python Windows 的 IDE

python - 在 Python DataFrame 中拆分字符串

python - 如何在具有各种数据类型的列表中搜索字符串,如果它们存在则对它们执行操作?