cgwebprojects
cgwebprojects

Reputation: 3472

Split words in a camelCased string before each uppercase letter

I have strings like:

$a = 'helloMister';
$b = 'doggyWaltz';
$c = 'bumWipe';
$d = 'pinkNips';

How can I explode at the capital letters?

Upvotes: 50

Views: 30812

Answers (5)

Bozzeo
Bozzeo

Reputation: 21

Further on the selected answer.

If you are dealing with acronyms in the text, it will change OOP to O O P

You can then use preg_split('/(?=[A-Z][a-z])/', $text) to lookahead for the lower case too to capture words fully.

Upvotes: 0

Ashwin Balani
Ashwin Balani

Reputation: 771

Extending Mathew's Answer, this works perfectly,

$arr = preg_replace("([A-Z])", " $0", $str);
$arr = explode(" ",trim($arr));

Upvotes: 0

Matthew
Matthew

Reputation: 25743

Look up preg_split

$result = preg_replace("([A-Z])", " $0", "helloMister");
print_r(explode(' ', $result));

hacky hack. Just don't have spaces in your input string.

Upvotes: 11

codaddict
codaddict

Reputation: 454912

If you want to split helloMister into hello and Mister you can use preg_split to split the string at a point just before the uppercase letter by using positive lookahead assertion:

$pieces = preg_split('/(?=[A-Z])/',$str);

and if you want to split it as hello and ister you can do:

$pieces = preg_split('/[A-Z]/',$str);

Upvotes: 122

atxdba
atxdba

Reputation: 5216

Look at preg_split, it's like explode but takes a regular expression

preg_split('~[A-Z]~',$inputString)

Upvotes: -1

Related Questions