Proper Case Function for PHP Strings
PHP has many built-in functions that manipulate strings. Several convert characters between uppercase and lowercase. The "strtolower" function converts all letters to lowercase; the "strtoupper" function converts all letters to uppercase. The "ucfirst" function converts the first word of a sentence to uppercase, and the "ucwords" function converts a sentence to proper case, with the first letter of each word capitalized. To exclude some words from conventional capitalization, you can write a custom function.
-
Capitalize the First Letter of a Sentence
-
To change a sentence so that the first letter of the first word in the sentence is in upper case, use the "ucfirst" function in PHP. For example, the statement:
echo ucfirst( "i can't believe it");
outputs "I can't believe it."
Capitalize the First Letter of Every Word
-
To convert all words in a string to proper case where the first letter of every word is capitalized, use the "ucwords" function in PHP. For example:
$s = "now is the time";
echo ucwords($s);
outputs "Now Is The Time"
-
Capitalizing when a String Is in Uppercase
-
To convert words to proper case when the words are already in capital letters, use a combination of the "ucwords" and "strtolower" functions. Use the "strtolower" function to convert all letters to lowercase and use the "ucwords" function on the result to convert each word to proper case. For example:
$string = "NOW IS THE TIME";
echo ucwords(strtolower($string));
outputs: "Now Is The Time."
Writing a Custom Proper Case Function
-
Write a custom function to exclude some words from being converted to proper case, such as "the" or "a." Break a sentence into words by separating the string on the space character using the "explode" function. Convert all words into lowercase and then into proper case except for a custom list of words you designate. Put the words back into a sentence using the "implode" function. For example:
function propercase($string) {
$words = explode(" ", $string);
foreach($words as $word) {
$word = strtolower($word);
if (!($word == "the" || $word == "a" || $word == "an" || $word == "of"))
$word = ucfirst($word);
return implode(" ", $words);
$string = "CAPITALIZE THE FIRST LETTER OF A STRING";
echo propercase($string);
outputs: "Capitalize the First Letter of a String"
-
References
- Photo Credit Hemera Technologies/AbleStock.com/Getty Images