Back to articles

in this post, we will see how to capitalize every first letter of a sentence, or a name. This post if the 3rd of my serie on PHP useful functions. You can find my other posts about Importing a CSV file in PHP and Export a PHP array in a CSV File.

This function is used to transform a string such as Jean-MARIE De la rue into Jean-Marie De La Rue

For this, we will create a custom fonction uc_first that takes the name of the user as a parameter and output a formatted string. This functions takes two parameters, but only the first one is required :

 function uc_first($name)
{
// @TODO Do something here
}

In a first time, we will make sure that the name passed is not null. This step is not required, but can help you some troubles.

if(null === $name) {
    return $name;
}

Description of the process

Then we will follow two distinct steps :

The first step is to create the regexp pattern. More information on Regular expressions is available here.

$pattern = "#([$delimiters])#";

Then you get an array containing all the elements, according to our regex:

$chunks = preg_split($pattern, $name,-1, PREG_SPLIT_DELIM_CAPTURE);

Using the flat PREG_SPLIT_DELIM_CAPTURE, allows use to keep the delimiters inside the chunks array.

Capitalize everything !

To finish, on every element cut, pass the chain into lowercase using strtolower then capitalize the first letter with ucfirst.

foreach ($chunks as &$n) {
    $n = ucfirst(strtolower($n));
}

We’re using here the character & within our foreach loop. It keeps the variable $n as a reference within the array $chunks. If the variable $n is updated then so is the corresponding line in the chunks array.

Then, the last step consists into reassembling the array into a string :

$name = implode('',$chunks);

return $name;

FINAL PHP FUNCTION :

Here is the final version of the function we just created :

/**
 *
 * This function allows you to add a capitalize letter to every letter of a word.
 *
 * @Exemple : "Jean-MARIE De la rue" will become "Jean-Marie De La Rue"
 *
 * @param string|null $name
 * @param string $delimiters
 *
 * @return string|null
 */
function uc_first($name,$delimiters = " -")
{
    // Return null name is not defined
    if(null === $name) {
        return $name;
    }

    // Here we use "-" and " " as separators. You can add every separator you want
    $pattern = "#([$delimiters])#";

    // Explode the string linked according to the pattern
    $chunks = preg_split($pattern, $name,-1, PREG_SPLIT_DELIM_CAPTURE);

    // On every chunk, we first put everything lowercase then uppercase the 1st character
    foreach ($chunks as &$n) {
        $n = ucfirst(strtolower($n));
    }

    // We re-link everything together
    $name = implode('',$chunks);

    return $name;
}

The code is available with a MIT license on github in the repository xusifob/lib

Don’t hesitate to leave a comment below !

Share this article