Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split at capital letters in PHP?

Tags:

php

preg-split

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?

like image 750
ShaShads Avatar asked Feb 27 '13 23:02

ShaShads


2 Answers

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.

like image 175
Kara Avatar answered Sep 22 '22 06:09

Kara


You need a positive-lookbehind. Try this:

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

array(2) {
  [0]=>
  string(5) "Camel"
  [1]=>
  string(4) "Case"
}
like image 21
Will Avatar answered Sep 24 '22 06:09

Will