Search code examples
phpcamelcasing

Insert space between two captalized words?


I have two words combined like KitnerCoster And I want to add a space in the middle, is there any sort of trick anyone knows if separating two words that are both capitalized and that is the only difference.


Solution

  • Do you care if the first word is capitalized? If not, do

    // ASCII
    preg_replace('/([a-z])([A-Z])/', '$1 $2', $string)
    preg_replace('/([[:lower:]])([[:upper:]])/', '$1 $2', $string)
    
    // Unicode (UTF-8)
    preg_replace('/(\p{Ll})(\p{Lu})/u', '$1 $2', $string)
    

    If you do care, and want to fix KitnerCostner but leave kitnerCostner alone, then do

    // ASCII
    preg_replace('/\b([A-Z]\S*[a-z])([A-Z])/', '$1 $2', $string)
    preg_replace('/\b([[:upper:]]\S*[[:lower:]])([[:upper:]])/', '$1 $2', $string)
    
    // Unicode (UTF-8)
    preg_replace('/\b(\p{Lu}\S*\p{Ll})(\p{Lu})/u', '$1 $2', $string)
    

    I've given versions that only match ASCII letters and ones that match all Unicode characters. The Unicode ones are available in PHP 5.1.0.