Search code examples
phparraysregexstringpreg-match

Extracting the parts of string into array


I have a string that I need to explode and get the information.

Sample string:

"20' Container 1, 40' Open Container 1, 40-45' Closed Container 3"

First I am exploding the string by , and getting

"20' Container 1"
"40' Open Container 1"
"40-45' Closed Container 3"

Now I want to explode the already exploded array as well so that I get the result in below format

array[
    0 => [
        0 => "20'"
        1 => "Container"
        2 => "1"
        ]
    1 => [
        0 => "40'"
        1 => "Open Container"
        2 => "1"
        ]
    ]

The strings may vary but it is decided that the format will be same e.g. length type number


Solution

  • Loop thru exploded string with comma delimiter, then push each matches base on length type number to result array

    $string = "20' Container 1, 40' Open Container 1, 40-45' Closed Container 3";
    
    $result = [];
    $pattern = '/([\d-]*\')\s(.*)\s(\d+)/';
    foreach (explode(', ', $string) as $value) {
        preg_match($pattern, $value, $matches); // Match length, type, number
        $result[] = array_slice($matches, 1);   // Slice with offset 1
    }
    
    print_r($result);