PHP

Smart Title Case

admin by @admin ADMIN
Jun 17, 2026
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Convert a string to title case while keeping common short words (a, an, the, of, etc.) lowercase — unless they appear at the start or end of the title.
PHP
Raw
<?php
function titleCase(string $text): string {
    static $small = ['a','an','and','as','at','but','by','en','for','if','in','of','on','or','the','to','vs','via'];
    $words = preg_split('/\s+/', mb_strtolower(trim($text)));
    $last  = count($words) - 1;
    foreach ($words as $i => $w) {
        if ($i === 0 || $i === $last || !in_array($w, $small, true)) {
            $words[$i] = mb_convert_case($w, MB_CASE_TITLE, 'UTF-8');
        }
    }
    return implode(' ', $words);
}

echo titleCase("the lord of the rings: the return of the king");
// The Lord of the Rings: the Return of the King
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.