1

I have for example string $s = 'A5C7'; and $s = 'A5C17';

I was try split string by symbols using preg_split('//', $s, -1, PREG_SPLIT_NO_EMPTY);

If string $s = 'A5C7' I got OK result like this:

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

but if use $s = 'A5C17' I got:

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

I wanna got like this:

 array(4) {
      [0]=>
      string(1) "A"
      [1]=>
      string(1) "5"
      [2]=>
      string(1) "C"
      [3]=>
      string(1) "17"
    }

How to improve preg_split('//', $s, -1, PREG_SPLIT_NO_EMPTY); for getting both type of results? Thanks in advance.

Rider_BY
  • 1,129
  • 1
  • 13
  • 31
  • Possible duplicate of [How to separate letters and digits from a string in php](http://stackoverflow.com/questions/4311156/how-to-separate-letters-and-digits-from-a-string-in-php) – Mohammad Feb 24 '17 at 08:54

1 Answers1

1

Using the pattern // will split characters. Try this instead:

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

array (
  0 => 'A',
  1 => '5',
  2 => 'C',
  3 => '17',
);

This pattern uses groups of consecutive integers as split delimiters, and it will capture what's between them. The option PREG_SPLIT_DELIM_CAPTURE makes it captures the delimiters (the integers) as well.

Aziz
  • 20,065
  • 8
  • 63
  • 69