How to explode a string on upper case characters
How to explode a string on upper case characters
Problem
You have a string with the following value “thisStringMustBeSplittedAfterUpperCase” and you want to obtain every word separately in an array, splitted after upper case.
Solution
1 |
$chunks = preg_split('/(?=[A-Z])/', $string, -1, PREG_SPLIT_NO_EMPTY); |
Output
The output of the $chunks array obtained with a var_dump($chunks) will be:
1 2 3 4 5 6 7 8 9 |
array (size=8) 0 => string 'this' (length=4) 1 => string 'String' (length=6) 2 => string 'Must' (length=4) 3 => string 'Be' (length=2) 4 => string 'Splitted' (length=8) 5 => string 'After' (length=5) 6 => string 'Upper' (length=5) 7 => string 'Case' (length=4) |
Solution in a function
1 2 3 4 5 6 |
function upperCaseSplit($string){ return preg_split('/(?=[A-Z])/', $string, -1, PREG_SPLIT_NO_EMPTY); } $string = 'thisStringMustBeSplittedAfterUpperCase'; var_dump (upperCaseSplit($string) ); |
The above example will have the same output but will be a more modular solution in case you want to use that in more than one place.