如何将字母数字字符串拆分为数组

时间:2015-01-05 19:08:10

标签: php arrays json

我有一个字母数字字符串

t14u1e7f8h15j4m3n50o65r22q29

我想把这个字符串转换成一个数组,为了节省空间我故意这样做。现在我面临的问题是,为了使用php将其转换为数组,顺序就像

data: [14, 1, 7, 8, ..]

categories : [t,u,e,f,h,j,m,n,o]

还可以进一步将类别转换为:

categories : [20:00,21:00,5:00,f,h,j,m,n,o]

where a => 1:00
      b => 2:00

由于顺序类似于t,u,e,f,h,j是否可以按字母顺序排列最多10个字符,即 距当前时间10小时categories [a,b,c,d,e,f,g,i,j,k]

1 个答案:

答案 0 :(得分:2)

这应该适合你:

(我假设你只使用小写字母)

<?php

    $string = "t14u1e7f8h15j4m3n50o65r22q29";
    $result = array("data" => array(), "categories" => array(), "categories" => array());


    preg_match_all("/\d+/", $string, $matches);
    $result["data"] = $matches[0];
    preg_match_all("/[^\d+]/", $string, $matches);
    $result["categories"] = $matches[0];

    foreach($result["categories"] as $v) {
        $result["categories2"][] = ord(strtolower($v))-96;
    }

    print_r($result);

?>

输出:

Array
(
    [data] => Array
        (
            [0] => 14
            [1] => 1
            [2] => 7
            [3] => 8
            [4] => 15
            [5] => 4
            [6] => 3
            [7] => 50
            [8] => 65
            [9] => 22
            [10] => 29
        )

    [categories] => Array
        (
            [0] => t
            [1] => u
            [2] => e
            [3] => f
            [4] => h
            [5] => j
            [6] => m
            [7] => n
            [8] => o
            [9] => r
            [10] => q
        )

    [categories2] => Array
        (
            [0] => 20
            [1] => 21
            [2] => 5
            [3] => 6
            [4] => 8
            [5] => 10
            [6] => 13
            [7] => 14
            [8] => 15
            [9] => 18
            [10] => 17
        )

)