使用PHP将波浪号分隔的字符串转换为数组

时间:2017-03-02 20:18:04

标签: php

如何在数组中转换后续字符串以及该字符串模式的通用名称是什么?

text^name1^Peter~text^secondname1^Wayland~text^email1^pw@Weyland-yutani.com~text^phone1^(000)000-00-00

1 个答案:

答案 0 :(得分:1)

~上拆分,然后将每个部分拆分为^

<?php

$data = 'text^name1^Peter~text^secondname1^Wayland~text^email1^pw@Weyland-yutani.com~text^phone1^(000)000-00-00';

$result = [];
foreach (explode('~', $data) as $keyvalue) {
    list($type, $key, $value) = explode('^', $keyvalue);
    $result[$key] = $value;
}

print_r($result);

结果:

Array
(
    [name1] => Peter
    [secondname1] => Wayland
    [email1] => pw@Weyland-yutani.com
    [phone1] => (000)000-00-00
)

请注意,这不会处理除&#34; text&#34;之外的任何其他记录类型,并且我不知道当值包含^~时会发生什么