dongzhenshen7435 2017-03-04 02:09
浏览 40
已采纳

PHP - 将包含特定编号的字符串转换为数组

I have a string containing a numeration like this:

$string = '01. Just an example 02. Another example 03. Just another example 04. Example.mp3 05. Test 123 06. Just an example again';

And now I want to convert this string (without any breaks) containing this numeration to an array that contains these items ("Just an example", "Another example", "Just another example" etc).

I cant' just use

$array = explode('.', $string);

because those items can also contain dots and other symbols or numbers like in my fourth item called "Example.mp3". The numeration goes up to about 50, but the amount of items isn't the same every time (sometimes I have just one item, but sometimes I have 2, 3 or even 15 items in this string). It doesn't always start with a 0.

How can I "convert" this string into an array without using the dot as separator but maybe using this whole numberation format and the dot together as a separator?

  • 写回答

2条回答 默认 最新

  • drxm72811 2017-03-04 02:23
    关注

    This is definitely not the best solution possible, but as far as I can tell it can handle almost any input pretty well.

    <?php
        $string = '01. Just an example 02. Another example 03. Just another example 04. Example.mp3 05. Test 123 06. Just an example again';
    
        $things=explode(' ',$string);
        $num=1;
    
        $your_output=array();
    
        foreach($things as $thing)
        {
                $num_padded = str_pad($num, 2, '0', STR_PAD_LEFT) .'.';
                if($num_padded==$thing)
                {
                        $num++;
                        $your_output[$num]='';
                }
                else
                        $your_output[$num].=' ' . $thing;
    
        }
    
        $final_result=array();
        foreach($your_output as $k=>$v)
        {
                $final_result[]=trim($v);
        }
    
        var_dump($final_result);
    
        ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误