【问题标题】:Get array from string从字符串中获取数组
【发布时间】:2019-12-03 11:08:10
【问题描述】:

我有字符串示例1234567899999987654321112309101

First 3 characters is data0
Second 2 characters is data1
Third 9 characters is data2
Fourth 5 characters is data3
Fifrt 12 characters is data4
First: 123
Second: 45
Third: 678999999
Fourth: 87654
Fifth: 321112309101

如何将这个字符串拆分为数据长度不同的数组。

【问题讨论】:

    标签: php arrays string split


    【解决方案1】:

    你可以使用substr()函数:

    $str = '1234567899999987654321112309101';
    $res = [];
    $res[] = substr($str,0,3);    // chars 1-3
    $res[] = substr($str,3,2);    // chars 4-5
    $res[] = substr($str,5,9);    // chars 6-14
    $res[] = substr($str,14,5);   // chars 15-19
    $res[] = substr($str,19,12);  // chars 20-31
    

    输出:

    Array
    (
        [0] => 123
        [1] => 45
        [2] => 678999999
        [3] => 87654
        [4] => 321112309101
    )
    

    Demo

    如果字符串太大并且你有一个定义的长度值数组,你可以使用这个循环:

    $str = '1234567899999987654321112309101';
    
    $len = [3,2,9,5,12];
    
    $res = [];
    $i = 0;
    foreach($len as $ind => $l){
        $res['data'.$ind] = substr($str,$i,$l);
        $i += $l;
    }
    

    输出:

    Array
    (
        [data0] => 123
        [data1] => 45
        [data2] => 678999999
        [data3] => 87654
        [data4] => 321112309101
    )
    

    Demo2

    【讨论】:

    • 好的,我知道这个解决方案,但是有内联解决方案吗?我有超过 100 个数据的 2048 长度字符串。
    • @Zuck19,检查一下。
    • @AksenP 他提到有超过 100 个数据,所以这两种解决方案都不起作用,在问题中他需要指定数据长度的分布。
    • @Zuck19 这应该是问题所在。你的问题太小了。尚不清楚with not same data length 是否会因数据点而异。添加三个样本以及如何将它们分开。
    • @Ajith,你不是 OP。他已经定义了几个数据的长度,所以,他可以很容易地创建$len数组。
    猜你喜欢
    • 2018-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-31
    • 1970-01-01
    • 2015-03-26
    • 1970-01-01
    相关资源
    最近更新 更多