Convert a String to Title Case Using PHP


Using PHP 8.1, PHP 8.2, PHP 8.3 and PHP 8.4, you can convert a string to title case (where the first letter of each word is capitalized) using the `ucwords()` function. This function capitalizes the first character of each word in a string.Heres an example:
<?php$string = "hello world! this is a test string.";// Convert to title case$titleCaseString = ucwords($string);echo $titleCaseString;?>
Output:
Hello World! This Is A Test String.
Explanation:- `ucwords()` capitalizes the first letter of each word in the string.- It works for all words separated by spaces.Custom Title Case Function (Handling Special Cases)If you need more control (e.g., handling hyphenated words or specific exceptions), you can create a custom function:
<?phpfunction customTitleCase($string) {// List of words to keep in lowercase (optional)$exceptions = ['a', 'an', 'the', 'and', 'but', 'or', 'for', 'nor', 'on', 'at', 'to', 'from', 'by', 'of', 'in', 'with'];// Convert the entire string to lowercase first$string = strtolower($string);// Split the string into words$words = explode(' ', $string);// Capitalize each word, except for exceptionsforeach ($words as &$word) {if (!in_array($word, $exceptions)) {$word = ucfirst($word);}}// Join the words back into a single stringreturn implode(' ', $words);}// Test the custom function$string = "hello world! this is a test string.";echo customTitleCase($string);?>
Output:
Hello World! This Is a Test String.
Explanation:1. The `customTitleCase` function first converts the entire string to lowercase.2. It then splits the string into an array of words.3. Each word is capitalized unless its in the `$exceptions` list (e.g., "a", "an", "the").4. Finally, the words are joined back into a single string.This approach gives you more flexibility for handling specific cases in title casing.