Search code examples
phpsplitpreg-split

Split a string after every second character


Okay, here is the question. I have a string. This string is a combination of US State Codes

$codes = 'ALAKAZARCACOCTDEDCFLGAHIIDILINIAKSKYLAMEMDMAMIMNMSMOMTNENVNHNJNMNYNCNDOHOKORPARISCSDTNTXUTVTVAWAWVWIWY';

I need to split the string into two letters, such as "AL", "AK", "AZ", "AR" etc.

I can't think of any other SIMPLE function other than preg_split but I am not an expert in regular expression.

Can any of you think about any other easy method to split the string ? The other function close to the answer what I can think of is using "substr". Looking for more options and also preg_split example.


Solution

  • This should work for you:

    <?php
    
        $codes = 'ALAKAZARCACOCTDEDCFLGAHIIDILINIAKSKYLAMEMDMAMIMNMSMOMTNENVNHNJNMNYNCNDOHOKORPARISCSDTNTXUTVTVAWAWVWIWY';  
        $arr = str_split($codes, 2);
        print_r($arr);
    
    ?>