Insert space between two captalized words?
-
26-09-2019 - |
Question
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.
OTHER TIPS
Using regular expressions you could do something like
s/([a-z])([A-Z])/'$1 $2'/g
However my first trial to write a regular expression usually fails so you might have to correct one or the other part.
How do you want to handle a 1-character long word? Like 'X' in FooXBar? The X will not be recognized as a separate word by the above regular expression.