12

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
  • 582
  • 4
  • 12

3 Answers3

22

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
  • 30,738
  • 21
  • 105
  • 131
Kara
  • 6,115
  • 16
  • 50
  • 57
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
  • 24,082
  • 14
  • 97
  • 108
  • 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
  • 22,354
  • 6
  • 52
  • 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