Search code examples
phppreg-matchpreg-match-all

Splitting string into chunks by applying some rules


I want to split abc49.99ab55.5def89de7 into chunks to get result (or similar) below. NOTE: only abc, ab, def and de are allowed. the numbers can be float.

Ideally this:

Array
(
    [abc] => 49.99
    [ab] => 55.5
    [def] => 89
    [de] => 7
)

This is fine too:

Array
(
    [0] => abc49.99
    [1] => ab55.5
    [2] => def89
    [3] => de7
)

After seeing some examples, I've come up with examples below but unfortunately cannot enhance them to meet the needs as defined above. Would you please help in this matter?

1

preg_match('/(?<fo>abc|ab)?(?<fn>\d*\.?\d*)(?<so>def|de)?(?<sn>\d*\.?\d*)?/', 'abc49.99ab55.5def89de7', $matches);

Array
(
    [0] => abc49.99
    [fo] => abc
    [1] => abc
    [fn] => 49.99
    [2] => 49.99
    [so] => 
    [3] => 
    [sn] => 
    [4] => 
)

2

preg_match_all('~^(.*?)(\d+)~m', 'abc49.99ab55.5def89de7', $matches);

Array
(
    [0] => Array
        (
            [0] => abc49
        )

    [1] => Array
        (
            [0] => abc
        )

    [2] => Array
        (
            [0] => 49
        )

)

Solution

  • As from OP's request. This should work for you:

    <?php
    
        $str = "abc49.99ab55.5def89de7";
        $arr = preg_split("/(?<=[0-9])(?=[a-z])/i", $str);
        print_r($arr);
    
    ?>
    

    regex explanation:

    /(?<=[0-9])(?=[a-z])/i
    
    • (?<=[0-9]) Positive Lookbehind - Assert that the regex below can be matched
      • [0-9] match a single character present in the list below
        • 0-9 a single character in the range between 0 and 9
    • (?=[a-z]) Positive Lookahead - Assert that the regex below can be matched
      • [a-z] match a single character present in the list below
        • a-z a single character in the range between a and z (case insensitive)

    flags:

    • i modifier: insensitive. Case insensitive match (ignores case of [a-zA-Z])