Search code examples
regexsplitpreg-match-allcamelcasing

RegEx and split camelCase


I want to get an array of all the words with capital letters that are included in the string. But only if the line begins with "set".

For example:

- string "setUserId", result array("User", "Id")
- string "getUserId", result false

Without limitation about "set" RegEx look like /([A-Z][a-z]+)/


Solution

  • $str ='setUserId';                          
    $rep_str = preg_replace('/^set/','',$str);
    if($str != $rep_str) {
            $array = preg_split('/(?<=[a-z])(?=[A-Z])/',$rep_str);
            var_dump($array);
    }
    

    See it

    Also your regex will also work.:

    $str = 'setUserId';
    if(preg_match('/^set/',$str) && preg_match_all('/([A-Z][a-z]*)/',$str,$match)) {
            var_dump($match[1]);                                                    
    }
    

    See it