Make first letter of each word/name uppercase, unless a known all-lowercase component of a surname

3k Views Asked by At

I use PHP to insert form entries into a MySQL database. Sometimes users enter text in all caps. Is there any way to change it so that only the first letters are capitalized? ucwords(strtolower($word)) won't work for me because I do not want to capitolize the first letter if it was not already capitalized.

My main concern is when people submit their last names. Most people submit it correctly, but some submit it as all caps. If it is all caps, it should work the same as ucwords(strtolower($word)), but if someone submits their name as De la Rosa, I wouldn't want it to change to De La Rosa.

3

There are 3 best solutions below

0
On
<?php

function ucwordsreplace($matches) {
    return ucwords(strtolower($matches[0]));
}

$original = "some UPPERCASE words GO HERE";
$fixed = preg_replace_callback('/\b[A-Z]+\b/', "ucwordsreplace", $original);

echo $fixed; // some Uppercase words Go Here

The regex matches only words which are entirely uppercase (any number of uppercase letters with a word boundary on each side) and then passes each of these to the defined function, which returns a replacement text with only the first letter capitalized.

If you want to also prevent things like UPPERCA$E then you could add other symbols to the regex, or even just match all non-lowercase characters (use [^a-z] instead of [A-Z]).

0
On

I think the function you denoted is correct..

But what's your exact requirement..

The following in the example for the usage of ucwords

<?php
$foo = 'hello world!';
$foo = ucwords($foo);             // Hello World! 

$bar = 'HELLO WORLD!';
$bar = ucwords($bar);             // HELLO WORLD!
$bar = ucwords(strtolower($bar)); // Hello World!
?> 

Else if u want only the first to be uppercase and not every first character of the string to be uppercase then try ucfirst() function.

0
On

ucfirst(strtolower($word));