Re: Re: ucwords() vs title case

From: Date: Mon, 30 Jun 2014 12:33:19 +0000
Subject: Re: Re: ucwords() vs title case
References: 1 2  Groups: php.internals 
Request: Send a blank email to internals+get-75142@lists.php.net to get a copy of this message
Andrea Faulds wrote (on 30/06/2014):
On 30 Jun 2014, at 12:54, Tjerk Meesters <tjerk.meesters@gmail.com> wrote:
Hi internals, I came across this old bug: https://bugs.php.net/bug.php?id=34407 Personally I find that the latter is too much of a departure from what we currently have; a compromise could be to treat punctuation as a word delimiter.
Hmm. Why not make it follow what \b in a regex would do, looking for “word boundaries”?
Unfortunately, the cleverer you try to be, the more edge cases you find. For instance, using \b will capitalise the 's' after an apostrophe, e.g. in "Andrea'S Suggestion". The function we have in our code base at the moment looks like this: function smart_uc_words($string) {
        $string = strtolower(trim($string));
        // Capitalise any word char preceded by a non-word char other than an apostrophe
        $string = preg_replace_callback('/(?<!\w|\')(\w)/', function($m){ return strtoupper($m[1]); }, $string);
        // Capitalise any word char which comes between an apostrophe and another word char
        $string = preg_replace_callback('/(?<=\')(\w)(?=\w)/', function($m){ return strtoupper($m[1]); }, $string);
        return $string;
} That still has problems: for instance abbreviations like "UK" and "USA" get forcibly title-cased, as do the dot-separated components of a domain name. I have been experimenting with the idea of leaving the string alone if it seems to be intentionally mixed case already, but that probably goes beyond the scope of what the built-in function should be doing. There's also problems with non-ASCII characters in the approach above. If you can guarantee the string is UTF-8, you can use mb_strtoupper(), replace \w with \p{L} and add the /u modifier to the regexes. An assumption core cannot make, unfortunately - probably a good example of why we need an explicitly Unicode string type, rather than byte-arrays which can be in any charset the user chooses. Regards, -- Rowan Collins [IMSoP]

« previous php.internals (#75142) next »