string split using regex PHP



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


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

2 Answers: 

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

  • /\d+|OK/ (96 steps) <-- Shammel's pattern
  • /OK|\d+/ (77 steps) #faster alternative first
  • /\d+|[^\d]{2} (74 steps) #make OK delimiter non-literal
  • /[^\d]{2}|\d+/ (55 steps) #faster alternative first

I'd say use the 55 steps one.


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.

// 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.


What you want is…

preg_match_all('(\d+|OK)', $string, $matches);
  • \d+ - One or more digits
  • | - or
  • OK - Capital O followed by capital K