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

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?

我有一个包含如下编号的字符串: p>

   $ string = '01。 只是一个例子02.另一个例子03.另一个例子04. Example.mp3 05.测试123 06.再一个例子'; 
  code>  pre> 
 
 

现在我想要 将包含此数字的此字符串(没有任何中断)转换为包含这些项的数组(“只是示例”,“另一个示例”,“只是另一个示例”等)。 p>

我不能只是使用 p>

  $ array = explode('。',$ string); 
  code>  pre> 
 
 

因为 这些项目还可以包含点和其他符号或数字,如我的第四个项目“Example.mp3”。 数字上升到大约50,但项目的数量每次都不一样(有时我只有一个项目,但有时我在这个字符串中有2个,3个甚至15个项目)。 它并不总是以0开头。 p>

如何在不使用点作为分隔符的情况下将此字符串“转换”为数组,但可以将整个数字格式和点一起使用为 分隔符? p> div>

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);

    ?>

Here is another option, I also removed the 0 from the first number.

$string = '1. Just an example 02. Another example 03. Just another example 04. Example.mp3 05. Test 123 06. Just an example again';
// Replace the digit format with an easy delimiter
$string_rep = preg_replace('/(\d{1,}\.\s?)/', '|', $string); 
// convert string to an array
$string_arr = explode('|', $string_rep);
// remove empty array entries
$clean = array_filter($string_arr);

print_r($clean);

/*
// result
Array
(
    [1] => Just an example 
    [2] => Another example 
    [3] => Just another example 
    [4] => Example.mp3 
    [5] => Test 123 
    [6] => Just an example again
)
*/