简体   繁体   中英

PHP - Convert a string containing a specific numeration into an array

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?

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
)
*/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM