php - 将带有两个定界符的字符串转换为平面关联数组

标签 php regex explode

<分区>

我真的不知道正则表达式... 所以我被卡住了......任何人都可以给我一个解释正则表达式本身的解决方案吗?

这是我的代码:

$str = "id:521082299088|name:JOHNSON GREIG DENOIA|mounth:JAN17|amount:170027|admin:2500|billqty:1|metre:R1/900|usage:00010261-00010550|reffno:0BKP21851AF3EC2E0D4F56997EA19DFA|charge:170377|balace:1935";
$pregsplit = preg_split("/[\s|]+/",$string2);

输出:

Array
(
    [0] => id:521082299088
    [1] => name:JOHNSON
    [2] => GREIG
    [3] => DENOIA
    [4] => mounth:JAN17
    [5] => amount:170027
    [6] => admin:2500
    [7] => billqty:1
    [8] => metre:R1/900
    [9] => usage:00010261-00010550
    [10] => reffno:0BKP21851AF3EC2E0D4F56997EA19DFA
    [11] => charge:170377
    [12] => balance:1935
)

我想要这样的输出:

Array
(
    "id" => 521082299088
    "name" => "JOHNSON GREIG DENOIA"
    "mount" => "JAN17"
    "amount" => 170027
    "admin" => 2500
    "billqty" => 1
    "metre" => "R1/900"
    "usage" => "00010261-00010550"
    "reffno" => "0BKP21851AF3EC2E0D4F56997EA19DFA"
    "charge" => 170377
    "balance" => 1935
)

最佳答案

1) 使用具有特定正则表达式模式的 preg_match_all 函数的解决方案:

$str = "id:521082299088|name:JOHNSON GREIG DENOIA|mounth:JAN17|amount:170027|admin:2500|billqty:1|metre:R1/900|usage:00010261-00010550|reffno:0BKP21851AF3EC2E0D4F56997EA19DFA|charge:170377|balace:1935";

preg_match_all("/(\w+):([^|]+)/", $str, $matches, PREG_SET_ORDER);
$result = [];
foreach ($matches as $items) {
    $result[$items[1]] = $items[2];
}
// $items[1] contains a "parameter" name captured by the first capturing group (\w+)
// $items[2] contains a "parameter" value captured by the second capturing group ([^|]+)

print_r($result);

输出:

Array
(
    [id] => 521082299088
    [name] => JOHNSON GREIG DENOIA
    [mounth] => JAN17
    [amount] => 170027
    [admin] => 2500
    [billqty] => 1
    [metre] => R1/900
    [usage] => 00010261-00010550
    [reffno] => 0BKP21851AF3EC2E0D4F56997EA19DFA
    [charge] => 170377
    [balace] => 1935
)

(\w+) - 匹配后跟 :

的所有字母数字字符

([^|]+) - 匹配除分隔符 | 之外的所有字符

http://php.net/manual/en/function.preg-match-all.php


2) 除了第一种方法 - 使用 array_combine 函数(合并来自两个捕获组的所有相应值):

preg_match_all("/(\w+):([^|]+)/", $str, $matches);
$result = array_combine($matches[1], $matches[2]);
// will give the same result

3) 第三种替代方法是使用 explode() 函数:

$result = [];
foreach (explode("|", $str) as $items) {
    $pair = explode(":", $items);
    $result[$pair[0]] = $pair[1];
}

关于php - 将带有两个定界符的字符串转换为平面关联数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41912366/

相关文章:

php - magento 删除管理菜单项

javascript - 数据表将输入搜索集中在 Bootstrap Modal 上

php - 为什么 PHP 需要闭包的 use 运算符?

regex - Z3 RegEx for Int*

php - 将反斜杠分隔的字符串转换为关联数组

php - 数字列表,同时删除除数字之外的所有内容

php - 为什么我的 Google 标记没有显示?

regex - Oracle 11g 通过正则表达式获取所有匹配的事件

javascript - 除了包含哈希的特定单词之外,在逗号内分割字符串

php - 获取行并分解 - PHP mySQL