Rider_BY Rider_BY - 9 months ago 27
PHP Question

Improve preg_split regex

I have input strings like this


"CC", 5, "B7C15", "B4C8"


I split out this strings via
preg_split
method.
But when input string
$str = 'CC';

method doesn't work.
My the code:

preg_split('/(\\d+)/', $string, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);


I get the output result:

array(4) {
[0]=>
string(1) "B"
[1]=>
string(1) "7"
[2]=>
string(1) "C"
[3]=>
string(2) "15"
}
array(1) {
[0]=>
string(1) "5"
}
array(4) {
[0]=>
string(1) "B"
[1]=>
string(1) "4"
[2]=>
string(1) "C"
[3]=>
string(2) "8"
}


Instead of the follow result as:

array(1) {
[0]=>
string(2) "CC"
}


I need to get the follow result as:

array(2) {
[0]=>
string(1) "C"
[1]=>
string(1) "C"
}


Thanks for advance.

Answer Source

Provided you need any non-digit character sequence split into one char elements, you only need to add (\D) (a single non-digit char group) as alternative to your regex:

preg_split('/(\\d+)|(\D)/', $string, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);

Demo: https://regex101.com/r/zFHybU/1