phpcpu-worduppercasepreg-splitpascalcasing

Split string of PascalCase words before each uppercase letter


I have string like:

SadnessSorrowSadnessSorrow

where words are concatenated without any space. Each word starts with a capital letter. I want to separate these words and select first 2 words to put in a new string.

I need to do this in a php application using preg_match function.

How should I go about it?

I tried using [A-Z], but somehow I am not getting it right.


Solution

  • Here, we can also split our string by the uppercase letters, maybe similar to:

    $str = "SadnessSorrowSadnessSorrow";
    
    $str_array = preg_split('/\B(?=[A-Z])/s', $str);
    
    foreach ($str_array as $value) {
        echo $value . "\n";
    }
    

    Based on bobble bubble's advice, it is much better to use \B(?=[A-Z]) instead of (?=[A-Z]), or we might use PREG_SPLIT_NO_EMPTY.

    Output

    Sadness
    Sorrow
    Sadness
    Sorrow