PHP: Best way to split string into alphabetic and numeric components

后端 未结 5 1516
情歌与酒
情歌与酒 2021-01-15 15:09

I have several strings of the format

AA11
AAAAAA1111111
AA1111111

Which is the best (most efficient) way to sepa

5条回答
  •  北海茫月
    2021-01-15 15:25

    This seems to work but when you try to pass something like "111111", it doesn't.

    In my application, I am expecting several scenarios and what seems to be doing the trick is this

    $referenceNumber = "AAA12132";
    $splited = preg_split('/(\d+)/', $referenceNumber, -1, PREG_SPLIT_DELIM_CAPTURE);
    var_dump($splited);
    

    Note:

    1. Getting an array of 2 elements, it means the 0th index is the alpha while the 1st is the numerics.
    2. Getting array of just 1 element, means the 0th element is the numeric and no alphas.
    3. If you get more than 2 array items, then your string must be in this format “AAA1323SDC”

    So given the above, you can play around with it based on your use case.

    Cheers!

提交回复
热议问题