phpregexsplit

string split using regex PHP


My string is "30OKOKOKOKOKOKOKOK30OKOKOKOKOKOKOKOKOKOKOKOKOKOK120" i want to split it in digits and 'OK' string, my expected output is

array(0=>30,1=>OK,2=>OK,......,n=>120)

currently i am using this

preg_match_all('!\d+!', $str, $matches);

but it only returns me digits i.e. 30,30,120 please help me to get above expected output


Solution

  • Starting from least efficient down to most efficient patterns, given your input sample:

    I'd say use the 55 steps one.

    $in = '30OKOKOKOKOKOKOKOK30OKOKOKOKOKOKOKOKOKOKOKOKOKOK120';
    var_export(preg_match_all('/\D{2}|\d+/', $in, $out) ? $out[0] : []);
    

    Note, preg_match_all() creates a multi-dim array.

    Another option is to use preg_split(). By using a couple of flags in its fourth parameter, the same result can be achieve with an amazingly brief pattern with minimal efficiency loss compared to my best pattern above.

    var_export(preg_split('/(OK)/', $in, 0, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE));
    // or /(\D{2})/
    

    This method returns a 1-dim array (not a true/false with a variable to reference) with a four-character pattern in 110 steps (or 104 with non-literal OK delimiting) . So for this case preg_match_all() is twice as fast.