Last Updated: February 25, 2016
· akhyar

Splitting string containing letters and numbers not separated by any particular delimiter in PHP

This snippet actually belong to someone in StackOverflow answered my question.

The problem is I want to explode a string with zero-width string delimiter. Like this:

- abc123 -> abc, 123
- 123abc -> 123, abc
- a1b2c3 -> a, 1, b, 2, c, 3
- abc123xyz -> abc, 123, xyz 

Here's the solution that I found closest to my need:

$string = "Hi, my name is Bob. I m 19yo and 170cm tall";
$parts = preg_split("/(,?\s+)|((?<=[a-z])(?=\d))|((?<=\d)(?=[a-z]))/i", $string);
var_dump ($parts);

Read the more detailed explanation here