Split words in a camelCased string before each uppercase letter
Asked Answered
H

5

50

I have strings like:

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

How can I explode at the capital letters?

Humbertohumble answered 25/1, 2012 at 5:44 Comment(0)
D
121

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);
Deerdre answered 25/1, 2012 at 5:48 Comment(5)
if first character is already uppercase this regex generates one empty element, if you want to ommit that you can use lcfirst first: $pieces = preg_split('/.(?=[A-Z])/',lcfirst($str));Spermatid
This is work fine if the first character is a lowercase, but Suppose we need to explode RecipesActionModel and we want only array of three elements Receipe,Action,Model. This solution make array with four elements which element 0 is empty.Multiplicand
Thank you so much for this, I was researching positive lookahead assertion, and your answer helps me out a lot!Boulanger
Wrap it with array_filter to get rid of any empty element.Binkley
Use this to avoid first empty element in case first element is upper case. preg_split('/(?=[A-Z])/', 'CamelCase', -1, PREG_SPLIT_NO_EMPTY);Horrific
M
11

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.

Millinery answered 25/1, 2012 at 5:53 Comment(1)
The parentheses are misleading at first glance and should not be used as delimiters (even if they are valid).Illiterate
T
0

Extending Mathew's Answer, this works perfectly,

$arr = preg_replace("([A-Z])", " $0", $str);
$arr = explode(" ",trim($arr));
Telepathist answered 24/7, 2020 at 21:26 Comment(0)
M
0

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.

Mika answered 6/4, 2023 at 12:32 Comment(0)
B
-1

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

preg_split('~[A-Z]~',$inputString)
Butte answered 25/1, 2012 at 5:48 Comment(2)
I was thinking the same thing, I assume they also want the capital letter as part of the 2nd word.Millinery
Cool this is nice, does this output an array?Humbertohumble

© 2022 - 2024 — McMap. All rights reserved.