How do You Convert a String to Title Case in PHP?

Hello Friends Today, through this tutorial, I will tell you How do you convert a string to title case in PHP With Example? In PHP, you can convert a string to title case using the `ucwords()` function. This function capitalizes the first letter of each word in a string. Here’s how you can use it:

<?php
$string = "hello world a title";
$titleCaseString = ucwords($string);
echo $titleCaseString; // Outputs: Hello World A Title
?>

This function takes an optional second parameter, `$delimiters`, which specifies a string containing the characters to be treated as word separators. If provided, the function will capitalize the first letter after each of these delimiters. If omitted, it defaults to `” \t\r\n\f\v”`, which includes space, tab, newline, carriage return, form feed, and vertical tab.

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.