Get the first letter of each word in a string

How would I get the first letter of each word for a given string?

$string = "Community College District";
$result = "CCD";

I found the javascript method but wasn't sure how to convert it to php.


explode() on the spaces, then you use the [] notation to access the resultant strings as arrays:

$words = explode(" ", "Community College District");
$acronym = "";

foreach ($words as $w) {
  $acronym .= $w[0];
}

If you have an expectation that multiple spaces may separate words, switch instead to preg_split()

$words = preg_split("/\s+/", "Community College District");

Or if characters other than whitespace delimit words (-,_) for example, use preg_split() as well:

// Delimit by multiple spaces, hyphen, underscore, comma
$words = preg_split("/[\s,_-]+/", "Community College District");

The best way to accomplish this is with regular expressions.

Lets break down what you want in a logical way: You want every character from the string is at the beginning of a word. The best way to identify those characters is to look for those characters that are preceded by white space.

So we start with a lookbehind for that space character, followed by any character:

/(?<=\s)./

This will find any character preceded by a space. But - the first character in the string is a character in the string is one you want extract. And because it's the first character in the string, it can't be preceded by a space. So we want to match anything preceded by a space or the first character in the string, so we add a start-of-subject assertion:

/(?<=\s|^)./

Now we are getting closer. But what if the string contains blocks of multiple spaces? What if it contains a space followed by a punctuation character? We probably don't want to match any of those, in fat we probably just want to match letters. We can do that with a character class [a-zA-Z]. And we can make are expression case-insensitive using the i modifier.

So we end up with:

/(?<=\s|^)[a-z]/i

But how do we actually use this in PHP? Well we want to match all occurrences of the regular expression within the string so we use (you guessed it) preg_match_all():

$string = "Progress in Veterinary Science";

$expr = '/(?<=\s|^)[a-z]/i';
preg_match_all($expr, $string, $matches);

Now we have all the characters we wanted to extract. To construct the result string you show, we need to join them together again:

$result = implode('', $matches[0]);

...and we need to ensure that they are all upper-case:

$result = strtoupper($result);

And that's really all there is to it.

See it working


Assuming the words are all split by spaces, this is a suitable solution:

$string = "Progress in Veterinary Science";

function initials($str) {
    $ret = '';
    foreach (explode(' ', $str) as $word)
        $ret .= strtoupper($word[0]);
    return $ret;
}

echo initials($string); // would output "PIVS"

There are a lot of explode answers. I think using the strtok function is a much more elegant and memory-efficient solution:

function createAcronym($string) {
    $output = null;
    $token  = strtok($string, ' ');
    while ($token !== false) {
        $output .= $token[0];
        $token = strtok(' ');
    }
    return $output;
}
$string = 'Progress in Veterinary Science';
echo createAcronym($string, false);

Here is a more robust and useful function, which supports UTF8 characters and the option to only use the capitalized words:

function createAcronym($string, $onlyCapitals = false) {
    $output = null;
    $token  = strtok($string, ' ');
    while ($token !== false) {
        $character = mb_substr($token, 0, 1);
        if ($onlyCapitals and mb_strtoupper($character) !== $character) {
            $token = strtok(' ');
            continue;
        }
        $output .= $character;
        $token = strtok(' ');
    }
    return $output;
}
$string = 'Leiðari í Kliniskum Útbúgvingum';
echo createAcronym($string);