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?
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.
You need a positive-lookbehind. Try this:
$parts = preg_split('/(?<=\\w)(?=[A-Z])/', 'CamelCase')
array(2) {
[0]=>
string(5) "Camel"
[1]=>
string(4) "Case"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With