Convert a String to Title Case Using PHP

In PHP, 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.

Here’s 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:

<?php
function 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 exceptions
foreach ($words as &$word) {
if (!in_array($word, $exceptions)) {
$word = ucfirst($word);
}
}

// Join the words back into a single string
return 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 it’s 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.