开发者

Insert space between two captalized words?

开发者 https://www.devze.com 2023-01-10 18:05 出处:网络
I have two words combined like KitnerCoster And I want to add a space in the middle, is there any sort of tri开发者_StackOverflowck anyone knows if separating two words that are both capitalized and t

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号