To::title()

Converts current value to title case.

Table of Contents
  1. Description
  2. Example

Description

To::title(?string $value): ?string;

This method converts current value to title case.

Example

echo To::title('lorem-ipsum'); // Returns `'Lorem Ipsum'`

This method uses a very simple way of converting text into title case. It has a lot of room for improvement such as to not capitalize the first letter in conjunctions and prepositions, and to be able to predict whether a sequence of characters is an abbreviation or a word based on the arrangement of vowels and consonants.

The only thing holding me back from improvising this method is that all the above rules are very language-specific. Developers can always change the behavior of this method simply by overriding it the same way when you were creating a new method:

To::_('title', static function (?string $value): ?string {
    if ("" === ($value = (string) $value)) {
        return null;
    }
    $value = preg_replace_callback('/\w+/', static function ($m) {
        if (in_array(strtolower($m[0]), ['and', 'as', 'at', /* … */])) {
            return $m[0];
        }
        return ucfirst($m[0]);
    }, $value);
    return "" !== $value ? ucfirst($value) : null;
});

To::title()

Converts current value to title case.