0

Basically I'd like to take a string like:

"D1F21a"

And turn it into an array like:

Array
(
    [0] => D
    [1] => 1
    [2] => F
    [3] => 21
    [4] => a
)

I've tried this solution but can't seem to successfully get it to work in PHP without getting Unknown modifier errors.

Community
  • 1
  • 1
user2145184
  • 440
  • 4
  • 15

3 Answers3

2

You could try to split the string at every number, capturing the numbers in the process:

$arr = preg_split('/(\d+)/', 'D1F21a', -1, PREG_SPLIT_DELIM_CAPTURE);

would result in:

array(5) {
  [0] => string(1) "D"
  [1] => string(1) "1"
  [2] => string(1) "F"
  [3] => string(2) "21"
  [4] => string(1) "a"
}
S22h
  • 553
  • 4
  • 16
0

The \K verb tells the engine to drop whatever it has matched so far from the match to be returned. Split the string.

\d+\K|\D+\K

Here is online demo

OR get the matched group from index 1

sample code:

$re = "/(\\d+\\K|\\D+\\K)/";
$str = "D1F21a";

preg_match_all($re, $str, $matches);

You can split it with Lookahead and Lookbehind from digit after non-digit and vice verse.

(?<=\D)(?=\d)|(?<=\d)(?=\D)

explanation:

\D  Non-Digit [^0-9]
\d  any digit [0-9]

Here is online demo

Braj
  • 46,415
  • 5
  • 60
  • 76
0

The regexp that you linked works as well:

$regexp = '/(?<=\p{L})(?=\p{N})|(?<=\p{N})(?=\p{L})/';
$data = "D1F21a";
$matches = preg_split($regexp, $data);
var_dump($matches);
Mark Baker
  • 209,507
  • 32
  • 346
  • 385