10

I found this similar question, but it doesn't answer my question, Split word by capital letter.

I have a string which is camel case. I want to break up that string at each capital letter like below.

$str = 'CamelCase'; // array('Camel', 'Case');

I have got this far:

$parts = preg_split('/(?=[A-Z])/', 'CamelCase');

But the resulting array always ends up with an empty value at the beginning! $parts looks like this

$parts = array('', 'Camel', 'Case');

How can I get rid of the empty value at the beginning of the array?

Community
  • 1
  • 1
ShaShads
  • 552
  • 4
  • 12

3 Answers3

19

You can use the PREG_SPLIT_NO_EMPTY flag like this:

$parts = preg_split('/(?=[A-Z])/', 'CamelCase', -1, PREG_SPLIT_NO_EMPTY);

See the documentation for preg_split.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Kara
  • 5,650
  • 15
  • 48
  • 55
3

You need a positive-lookbehind. Try this:

$parts = preg_split('/(?<=\\w)(?=[A-Z])/', 'CamelCase')

array(2) {
  [0]=>
  string(5) "Camel"
  [1]=>
  string(4) "Case"
}
Will
  • 21,498
  • 11
  • 84
  • 98
  • Seems to not work with `C CamelCase`, might need adjustment if there may be spaces. – Wesley Murch Feb 27 '13 at 23:41
  • @Wesley, spaces weren't in the original requirement, but this would work: preg_split('/(?:(?<=\\w)(?=[A-Z])| )/', 'C CamelCase') – Will Feb 28 '13 at 00:07
2

Array filter can be used to remove all empty values:

$parts = array_filter( $parts, 'strlen' );
Jim
  • 21,521
  • 5
  • 49
  • 80
  • 1
    He wants to generate the correct array, not fix the broken one. – Will Feb 27 '13 at 23:40
  • 1
    Given Kara's answer this isn't the best answer but, in my defence, the asker specifically asked "How can I get rid of the empty value at the beggining of the array?" – Jim Feb 28 '13 at 00:12