This isn't something I'd normally use a regex for, but my solution isn't exactly what you would call "beautiful":
$string = join("", map(ucfirst, split(/(\s+)/, $string)));
That split()
s the string by whitespace and captures all the whitespace, then goes through each element of the list and does ucfirst
on them (making the first character uppercase), then join()
s them back together as a single string. Not awful, but perhaps you'll like a regex more. I personally just don't like \Q
or \U
or other semi-awkward regex constructs.
EDIT: Someone else mentioned that punctuation might be a potential issue. If, say, you want this:
...string
changed to this:
...String
i.e. you want words capitalized even if there is punctuation before them, try something more like this:
$string = join("", map(ucfirst, split(/(\w+)/, $string)));
Same thing, but it split()
s on words (\w+
) so that the captured elements of the list are word-only. Same overall effect, but will capitalize words that may not start with a word character. Change \w
to [a-zA-Z]
to eliminate trying to capitalize numbers. And just generally tweak it however you like.