Split string by letter sets with numbers

1

I have the following string in a particular array:

[est] => INA1C4A1

I need to split into sets:

 [0] => Array
     (
        [mov] => IN
        [seq] => Array
                (
                   [0] => A1
                   [1] => C4
                   [2] => A1
                )

its easy! , but the problem is that "A1" can be "A11", so I thought I'd split into sets until the first character appeared:

for($i=0;$i<sizeof($arr_res);$i++){
    $aux[$i][mov] =  substr($arr_res[$i][cod], 0, 2);
    $aux_mov =  substr($arr_res[$i][codigo], 2, strlen($arr_res[$i][codigo])-1);

    $aux[$i][seq] = preg_split('/(?=[0-9]+)/',$aux_mov,3);
}

the result is not as expected:

[0] => Array
        (
            [mov] => IN
            [seq] => Array
                (
                    [0] => A
                    [1] => 1C
                    [2] => 4A1
                )

Is this the problem '/ (? = [0-9] +) /' ?

    
asked by anonymous 15.12.2016 / 15:48

1 answer

2

In order to capture these sets individually, do not split the string, make the capture using preg_match_all() so you define which parts will get the string.

preg_split() will split the string in equal parts according to the delimiter, which is not very suitable for this situation.

[A-Z]\d{1,2} means caputra a capital letter between A and Z followed by a or even two digits (0-9)

Note that if the set has 3 or more characters, only the first two characters will be married, the rest will be discarded.

Ideone example

$str = 'INA1C4A1';

preg_match_all('/[A-Z]\d{1,2}/', $str, $m);

echo "<pre>";
print_r($m);

Output:

Array
(
    [0] => Array
        (
            [0] => A1
            [1] => C4
            [2] => A1
        )

)
    
15.12.2016 / 15:55