Split string by letter sets with numbers

Asked

Viewed 166 times

1

I have the following string in a given array:

[est] => INA1C4A1

I need to divide into sets:

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

its easy!, but the problem is that the "A1" can be "A11", so I thought divide into sets until the first character appears:

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
                )

This is the problem '/(?=[0-9]+)/'?

  • "IN" (mov) is what? How is it to extract?

  • @Miguel The "IN" is already extracted in " $aux[$i][mov] = substr($arr_res[$i][Cod], 0, 2); "my question is " preg_split "

1 answer

2


To capture 'individually' these sets do not break (split) the string, capture using preg_match_all() so you define which parts will pick up from the string.

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

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

Be aware that if the set has 3 or more characters only the first two will be married, the others will be discarded.

Ideone example

$str = 'INA1C4A1';

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

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

Exit:

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

)
  • Thank you, I was not on the right track. Now I understand.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.