Search code examples
phppreg-split

Split string before each uppercase letter of a StudlyCase (PascalCase) string without empty elements


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?


Solution

  • 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.