phpstringsplituppercasecamelcasing

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?


Solution

  • 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);