2

I'm using PHP. Given, for example, the following string:

$str = "a2c4-8|a6c2,c3-5,c6[2],c8[4]-10,c14-21[5]|a30"

and exploding it by | I get the strings:

a2c4-8
a6c2,c3-5,c6[2],c8[4]-10,c14-21[5]
a30

Now I would like to separate the digits that follow the a from all the other characters, remove the letters a and c (keep dashes, commas and square brackets) and place the results in a multidimensional array as follows:

Array
(
    [0] => Array
        (
            [a] => 2
            [c] => 4-8
        )

    [1] => Array
        (
            [a] => 6
            [c] => 2,3-5,6[2],8[4]-10,14-21[5]
    )

    [2] => Array
        (
            [a] => 30
            [c] => 
        )

)

a is always followed by digit and after this digit there may be or may not be a c followed by other comma separated strings.

Notice that in the resulting array the letters a and c have been removed. All other characters have been kept. I tried to modify this answer by Casimir et Hippolyte but without success.

A plus would be avoid to add to the resulting array empty array keys (as the last [c] above).

1
  • After exploding you probably want to use a regex to match the different parts and then just put them into the result array (Something like this: 3v4l.org/XoIb1). Commented Jun 28, 2016 at 15:46

1 Answer 1

1

Consider the following solution using preg_match_all function with named submasks((?P<a>)...) and PREG_SET_ORDER flag, array_map, array_filter, array_column(available since PHP 5.5) and trim functions:

$str = "a2c4-8|a6c2,c3-5,c6[2],c8[4]-10,c14-21[5]|a30";
$parts = explode("|", $str);

$result = array_map(function ($v) {
    preg_match_all("/(?P<a>a\d+)?(?P<c>c[0-9-\[\]]+)?/", $v, $matches, PREG_SET_ORDER);
    $arr = [];
    $a_numbers = array_filter(array_column($matches, "a"));
    $c_numbers = array_filter(array_column($matches, "c"));
    if (!empty($a_numbers)) {
        $arr['a'] = array_map(function($v){ return trim($v, 'a'); }, $a_numbers)[0];
    }
    if (!empty($c_numbers)) {
        $arr['c'] = implode(",", array_map(function($v){ return trim($v, 'c'); }, $c_numbers));
    }

    return $arr;
}, $parts);

print_r($result);

The output:

Array
(
    [0] => Array
        (
            [a] => 2
            [c] => 4-8
        )

    [1] => Array
        (
            [a] => 6
            [c] => 2,3-5,6[2],8[4]-10,14-21[5]
        )

    [2] => Array
        (
            [a] => 30
        )
)

P.S. "empty array keys" are also omitted

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.