Hello,
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 seperating two words that are both captalized and that is the only difference.
Regards,
Hello,
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 seperating two words that are both captalized and that is the only difference.
Regards,
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.
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.