What is the name of the first letter in a word

Is there a word for the first letter of a sentence (i in this sentence)?

Is there a word for the first letter of each word in a sentence (itawftfloewias in this case)?

I understand that as terms, this could be described as an acrostic for the former, and an acrostic, acronym or an initialism for the latter case, but I’m wondering if this can describe the letters themselves, or just the subsequent output. edit: Please note that this is not the answer, just a suggestion, and it isn’t correct use of these terms

My best guess would be initial for the latter, but I have no idea for the former — maybe acrostic would be a good choice

asked Feb 19, 2021 at 12:56

Nick Bull's user avatar

Nick BullNick Bull

4473 silver badges8 bronze badges

10

Since EL&U prefers to have answers as answers rather than have them buried in the comments, I will here repeat a suggestion I made in the comments that the OP liked.

While initial does not by default describe the first letter of anything except names (and also the large letter beginning a text or a division or paragraph), I think it would be OK to say, somewhere in your text, ‘I am going to use the term the sentence initial to refer to the first letter of a sentence, and the initials of the sentence to refer to the first letters of the words in a sentence.’

There are many variations on this general theme possible, e.g. word initial, as the OP themself suggested in a comment.

answered Feb 19, 2021 at 15:33

linguisticturn's user avatar

linguisticturnlinguisticturn

12.1k2 gold badges26 silver badges50 bronze badges

4

Initial is actually also used for the first case, especially when referring to elaborated letters in historical books, like this capital O:

Conversation-saints 01.jpg
from Princeton, Public Domain, Link

answered Feb 19, 2021 at 13:09

Glorfindel's user avatar

GlorfindelGlorfindel

14.4k15 gold badges66 silver badges58 bronze badges

5

Initials are very important to understand as they’re used in a variety of important documents throughout one’s life. If you don’t know what initials are or how they work, you’ve come to the right place.

Initials are simply the first letter of a word. They are most commonly used with people’s names and should represent the first letter of the first name and the first letter of the second name. For example, John Smith would have JS initials.

What Are Initials?

You’ll come across initials plenty of times in English, especially anyone who has to fill in important documents. Documents often ask you to sign your initials directly after the place where you’ve signed your name and dated it.

Examples Of What Initials Are

We could teach you everything we know about initials, but it wouldn’t be much help if you don’t see them in action. We thought we’d show you some examples of how initials are used, as well as the names that those initials come from.

Remember, we must initial a name in its entirety. It’s no good only initially a first name or a last name. Both names must be included together. A typical initial is two letters long, though sometimes you can have more than that depending on the name.

  1. My name is Jack Preacher, and my initials are JP.
  2. If your name is John O’Sullivan, your initials can be JOS or JO, depending on your preference.
  3. I am called Steve Arnott, and my initials are SA.
  4. My initials are MO. My name is Matthew Oscar.
  5. Where do I find my initials if my name is Dean West? Is DW correct?
  6. You should initial all parts of your name. Patrick Stewart becomes PS.
  7. Matthew Bolton is initialed as MB.
  8. Make sure to initial your first name and last name, Roger Fox. That would make it RF.
  9. Mrs. Tonks’ initials are ST; I wonder what her first name could be. Sarah? Sam?
  10. My initials are AJ, and my first name is Alex. Can you guess my surname?
  11. The name is James Blond, though you can refer to me as JB.
  12. My initials are MS, and my name is Mary Sue.

We included as many names and examples as we could to show you when initials are used. Typically, we would know both the first name and the surname (second name) of the person if we’re initialing them, though we also only tend to give ourselves initials.

However, in the case of the teacher example (example 9), sometimes you will see an initial without knowing a full name. This leaves the name guessing to speculation, as an initial only gives away the first letter of a name and not the full name.

Are Initials Always First And Last Name?

Whenever you want to write initials, it always includes your first and last name. There are no other names that must be included for an initial to be authentic.

Most initials are two letters long because they are only a first and last name (AJ or BT). However, if the name has more than one word in it (usually indicated by a second capital letter), it’s possible to have three or more letters in the initial.

Let’s look at a few examples of what we mean:

  • My name is AJ Prince. My initials are AJP.

Here, AJ already has an initial in his first name. Usually, the J in an initial like this means “Junior,” as their mother or father share the same name as them. However, AJ also has to include his last name initial to be correct, so he has three initials in his name.

  • My name is John O’Peters. My initials are JOP.

Because the surname O’Peters uses two capital letters, it’s possible to see the initials of the full name be three letters in length. However, this is usually down to personal preference. Some people with “O’Peters” as a surname might only want to keep the O as the initial, while others want to keep the OP.

Is Initial Middle Name?

Whenever we’re using initials, we don’t typically include a middle name. There are a few exceptions, but most formal documents don’t require a middle name to be stated.

For example, if your name is “John Paul Goldberg,” your initials would be JG. You won’t need to include the P from Paul in your middle name. There is one exception to this rule, and that all comes down to personal preference again.

If you already initial your middle name when you introduce yourself (i.e., John F. Kennedy or Lyndon B. Johnson), then you can put those initials in your name. JFK and LBJ were both US Presidents who used their middle initial.

The tradition to use a middle initial when writing your initials is an American tradition, and it doesn’t typically happen anywhere else in the world. However, if you want to use your middle initial, there is nothing wrong with doing so – it’s just not common.

How Do I Write My Initials?

Let’s go over a quick guide to writing your initials. If you’ve been asked to do so, it can’t be much simpler than this!

  1. Write your full name.
  2. George Patrick Johnson.
  3. Remove your middle name if you don’t use the initial.
  4. George Johnson.
  5. Find the first letter of your first name and remove the rest.
  6. G Johnson
  7. Now find the first letter of your second name and remove the rest.
  8. G J
  9. Now put the two initials together. There doesn’t need to be a space between them.
  10. GJ

How Do I Write My Initials And Surname?

Sometimes, you might see initials used for only one name. If this is the case, you’ll always see the first name initialed, but the last name will be written out in full.

For example, a writer might sign their work “L. Bury.” If the writer’s first name is Lucian, then we can see how they’ve initialed it to show only “L.”

But why do writers do this?

Well, it’s not just writers that address themselves in this way. It’s actually common practice for a lot of people in the arts industry. For example, an artist might sign their work to say P. Picasso, or a playwright might write W. Shakespeare.

The reason this is done is as a sign of recognition. Most people will be familiar with the writer that they’re reading from or the artist they’re looking at the art of. If you’re famous enough in your own circle of art, then people won’t need to know your full name.

For that reason, it’s common to see the first name initialized when written. Your last name is more than enough to recognize you with when you’re well-established in your respected field. For newer writers and artists, it’s best to write your full name, so people know who you are before trying to remove some of your initials.

What To Write If A Form Asks For Your Initials

The most common place you might find something asking for your initials is on a form or a contract of some kind. You’ll typically see it look as follows:

Signature:Put signature here

Printed Name:DEAN EDWARDS

Initials:DE

Date:9/12/2021

You’ll almost always write your full name out and then include the initials afterward. It just helps to streamline the form-filling process and helps with the analysis of the form on the back-end.

How Do You Punctuate Initials?

You don’t always need to punctuate initials. It’s actually more common to leave your initials without any punctuation. However, some people like to show a difference between the two letters that separate their names with periods.

  • DE
  • D.E.

Both of these forms of initials are correctly punctuated. It’s up to you which form works best for you, but most people like to use it without periods because it saves time.

It’s worth quickly mentioning that if you follow the writer’s method above where the first name is initialed, but the last name is spelled out, you always want a period at the end of that.

  • D. Edwards

This is because your spelling out the last name after the initial, so it’s good to separate the two with a period and a space.

Do You Put Periods Between Initials?

As we’ve already said, it’s up to you how you want to punctuate your initials. The most common form of punctuation uses periods between initials. If that looks good to you, then we recommend you use it!

Most people leave the periods out and only write the two letters when they initial their name.

Why Do Writers Use Initials?

Writers use initials when for two reasons.

They are either already well-established writers whose initials are recognizable to the people familiar with their work. They might also use them because they want to save time, and it’s quicker to write two letters than it is to write a full name.

How Do You Write Juniors Initials?

We briefly touched on this earlier, but if you share the same name with your child (or vise versa), you may want to know what their junior initials are.

  • If you’re called Andy, and your son is called Andy, his name will be Andy Junior.
  • Andy Junior is initialed to be AJ.
  • If you include the surname after this, you simply add the next initial onto AJ.
  • AJT works as a good initial. (If your last name begins with T).

martin lassen dam grammarhow

Martin holds a Master’s degree in Finance and International Business. He has six years of experience in professional communication with clients, executives, and colleagues. Furthermore, he has teaching experience from Aarhus University. Martin has been featured as an expert in communication and teaching on Forbes and Shopify. Read more about Martin here.

Subjects>Hobbies>Toys & Games

User Avatar

Wiki User

∙ 14y ago


Best Answer

Copy

The ‘Initial’

User Avatar

Wiki User

∙ 14y ago

This answer is:

User Avatar

Study guides

More answers

User Avatar

Anonymous

Lvl 1

∙ 2y ago

Copy

An I oop an I oop

This answer is:

Add your answer:

Earn +

20

pts

Q: What is the first letter of a word called?

Write your answer…

Submit

Still have questions?

magnify glass

imp

Related questions

People also asked

The first letters of these words that name things in the pictures make up a new word. What is it? Write it.

The word is … .

Задание рисунок 1

reshalka.com

ГДЗ Английский язык 5 класс (часть 1) Афанасьева. UNIT 2. Step 10. Номер №8

Решение

Перевод задания
Первые буквы этих слов образуют новое слово. Какое? Напиши.
Слово − … .

 
ОТВЕТ
1. Mouse.
2. Orange.
3. Up.
4. Nine.
5. Train.
6. Ant.
7. Ice cream.
8. Nest

The word is “MOUNTAIN”

Перевод ответа
1. Мышь;
2. Апельсин;
3. Вверх;
4. Девять;
5. Поезд;
6. Муравей;
7. Мороженое;
8. Гнездо.
Слово – «ГОРА»

explode() on the spaces, then you use an appropriate substring method to access the first character of each word.

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

foreach ($words as $w) {
  $acronym .= mb_substr($w, 0, 1);
}

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");

answered Mar 14, 2012 at 16:58

Michael Berkowski's user avatar

Michael BerkowskiMichael Berkowski

266k46 gold badges443 silver badges388 bronze badges

2

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 «any word character» w escape sequence. And we can make are expression case-insensitive using the i modifier as well as u modifier to support utf-8 characters.

So we end up with:

/(?<=s|^)w/iu

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|^)w/iu';
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 = mb_strtoupper($result);

And that’s really all there is to it.

See it working


Here’s a slightly compressed version, using the alternative regex from Leigh’s comment to «capture the initial letters of words separated by hyphens, full stops, etc.» (rather than only spaces.)

$str="Foo Bar";
preg_match_all('/(?<=b)w/iu',$str,$matches);
$result=mb_strtoupper(implode('',$matches[0]));

5

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"

answered Apr 23, 2013 at 8:34

casraf's user avatar

casrafcasraf

20.7k8 gold badges55 silver badges91 bronze badges

5

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);

answered Apr 23, 2013 at 8:49

Sverri M. Olsen's user avatar

Sverri M. OlsenSverri M. Olsen

13k3 gold badges36 silver badges52 bronze badges

6

As explained by others, classical way consist in iterating over each word of your initial string, reduce the word to its first letter, and combine those first letters together.

Here is a helper method combining the different steps.

/**
 * @return string
 */
function getInitials($string = null) {
    return array_reduce(
        explode(' ', $string),
        function ($initials, $word) {
            return sprintf('%s%s', $initials, substr($word, 0, 1));
        },
        ''
    );
}

NB : this will return an empty string in case the given string is empty.

getInitials('Community College District')

string ‘CCD’ (length=3)

getInitials()

string » (length=0)

getInitials('Lorem ipsum dolor sic amet')

string ‘Lidsa’ (length=5)

Of course you can add filters to the callback function of array_reduce(), such as strtoupper() if you prefer only uppercased initials for instance.

answered Mar 26, 2017 at 11:53

Flo Schild's user avatar

Flo SchildFlo Schild

4,9744 gold badges39 silver badges55 bronze badges

Michael Berkowski‘s (and others) answer, simplified to one line and working correctly on multi-byte characters (i.e. making abbreviation / initials out of non-Latin string):

foreach(explode(' ', $words) as $word) $acronym .= mb_substr($word, 0, 1, 'utf-8');

Using mb_substr($word, 0, 1, 'utf-8'), instead of $word[0] seems to be must, if you’re working on non-Latin, multi-byte strings and characters, i.e. when using UTF-8 encoded strings.

answered Aug 25, 2014 at 9:16

trejder's user avatar

trejdertrejder

17k27 gold badges123 silver badges215 bronze badges

0

$temp = explode(' ', $string);
$result = '';
foreach($temp as $t)
    $result .= $t[0];

answered Mar 14, 2012 at 16:58

Ascherer's user avatar

AschererAscherer

8,1933 gold badges42 silver badges60 bronze badges

Like this

preg_match_all('#(?<=s|b)pL#u', $String, $Result);
echo '<pre>' . print_r($Result, 1) . '</pre>';

answered Apr 23, 2013 at 8:45

Winston's user avatar

WinstonWinston

1,7482 gold badges17 silver badges29 bronze badges

6

$str = 'I am a String!';
echo implode('', array_map(function($v) { return $v[0]; }, explode(' ', $str)));

// would output IaaS

answered May 28, 2013 at 11:38

billyonecan's user avatar

billyonecanbillyonecan

20k8 gold badges42 silver badges64 bronze badges

Something I’ve cooked up.

/**
 * Return the first letter of each word in uppercase - if it's too long.
 *
 * @param string $str
 * @param int $max
 * @param string $acronym
 * @return string
 */
function str_acronym($str, $max = 12, $acronym = '')
{
    if (strlen($str) <= $max) return $str;

    $words = explode(' ', $str);

    foreach ($words as $word)
    {
        $acronym .= strtoupper(substr($word, 0, 1));
    }

    return $acronym;
}

answered Oct 12, 2015 at 11:41

function acronym( $string = '' ) {
    $words = explode(' ', $string);
    if ( ! $words ) {
        return false;
    }
    $result = '';
    foreach ( $words as $word ) $result .= $word[0];
    return strtoupper( $result );
}

answered Mar 14, 2012 at 17:06

smassey's user avatar

smasseysmassey

5,82523 silver badges37 bronze badges

Why not using the str_word_count function for this?

  1. get each word as a row in an array
  2. reduce that array to the first letter

    $acronym = array_reduce(
    str_word_count(«Community College District», 1),
    function($res , $w){
    return $res . $w[0];
    }
    );

answered Mar 1, 2019 at 13:39

Spir's user avatar

SpirSpir

1,7071 gold badge16 silver badges27 bronze badges

Assuming that the original string is properly built (trimmed and without double spaces), this is what I do:

$name = 'John Doe';
$initials = implode( '', array_map( function ( $part ) { 
    return strtoupper( $part['0'] );
}, explode( ' ', $name ) ) );

Basically, breaking the string into words, extracting & capitalizing the first character of a word, and gluing them back together.

answered Feb 2, 2021 at 15:55

Hike Nalbandyan's user avatar

Hike NalbandyanHike Nalbandyan

9441 gold badge10 silver badges28 bronze badges

I think you have to explode and join them back again …..

<?php
$string  = "Progress in Veterinary Science";
$pieces = explode(" ", $string);
$str="";
foreach($pieces as $piece)
{
    $str.=$piece[0];
}    
echo $str; /// it will result into  "PiVS"
?>

answered Apr 23, 2013 at 8:37

Ravindra Shekhawat's user avatar

Using Prateeks foundation, here’s a simple example with explanations

//  initialize variables
$string = 'Capitalize Each First Word In A String';
$myCapitalizedString = '';

//  here's the code
$strs=explode(" ",$string);    
foreach($strs as $str) {
  $myCapitalizedString .= $str[0]; 
}

//  output
echo $myCapitalizedString;  // prints 'CEFWIAS'

answered Jun 2, 2013 at 8:29

Rob Stocki's user avatar

Rob StockiRob Stocki

1461 silver badge9 bronze badges

0

If there are more number of spaces between two letters in the input string then try this.

function first_letter($str)
{
    $arr2 = array_filter(array_map('trim',explode(' ', $str)));
    $result='';
    foreach($arr2 as $v)
    {
        $result.=$v[0];
    }
    return $result;
}

$str="    Let's   try   with    more   spaces       for  fun .   ";

echo first_letter($str);

Demo1

Alternative of same code

function first_letter($str)
{
    return implode('', array_map(function($v) { return $v[0]; },array_filter(array_map('trim',explode(' ', $str)))));;
}

$str="    Let's   try   with    more   spaces       for  fun .   ";

echo first_letter($str);

Demo2

answered Feb 26, 2016 at 12:43

Durgesh Tiwari's user avatar

Here’s a function that gets you the initials of a name and if the initials are only 1 letter then it returns the first 2 letters of the first name.

function getNameInitials($name) {

    preg_match_all('#(?<=s|b)pL#u', $name, $res);
    $initials = implode('', $res[0]);

    if (strlen($initials) < 2) {
        $initials = strtoupper(substr($name, 0, 2));
    }

    return strtoupper($initials);
}

answered May 9, 2018 at 14:55

Salam's user avatar

SalamSalam

1,03214 silver badges19 bronze badges

1

Try this-

$strs=explode(" ",$string);

foreach($strs as $str)
  echo $str[0];

answered Apr 23, 2013 at 8:34

Prateek Shukla's user avatar

Prateek ShuklaPrateek Shukla

5932 gold badges7 silver badges27 bronze badges

Something like this should do the trick :

$string = 'Some words in a string';
$words = explode(' ', $string); // array of word
foreach($words as $word){
    echo $word[0]; // first letter
}

answered Apr 23, 2013 at 8:37

Marshall's user avatar

MarshallMarshall

3291 silver badge7 bronze badges

For the case that you’ll be doing this on large strings (or even directly from file) explode() isn’t the best way to do this. Imagine how much memory will get wasted if you have to split string 2MB large into memory.

With little more coding and (assuming PHP >= 5.0) you can easily implement PHP’s Iterator class that will do exactly this. This will be close to generator in python and long story short, here’s the code:

/**
 * Class for CONTINOUS reading of words from string.
*/
class WordsIterator implements Iterator {
    private $pos = 0;
    private $str = '';
    private $index = 0;
    private $current = null;

    // Regexp explained:
    // ([^\w]*?) - Eat everything non-word before actual word characters
    //              Mostly used only if string beings with non-word char
    // ([\w]+)   - Word
    // ([^\w]+?|$) - Trailing thrash
    private $re = '~([^\w]*?)([\w]+)([^\w]+?|$)~imsS';

    // Primary initialize string
    public function __construct($str) {
        $this->str = $str;
    }

    // Restart indexing
    function rewind() {
        $this->pos = 0;
        $this->index = 0;
        $this->current = null;
    }

    // Fetches current word
    function current() {
        return $this->current;
    }

    // Return id of word you are currently at (you can use offset too)
    function key() {
        return $this->index;
    }

    // Here's where the magic is done
    function next() {
        if( $this->pos < 0){
            return;
        }

        $match = array();
        ++$this->index;

        // If we can't find any another piece that matches... Set pos to -1
        // and stop function
        if( !preg_match( $this->re, $this->str, $match, 0, $this->pos)){
            $this->current = null;
            $this->pos = -1;
            return;
        }

        // Skip what we have read now
        $this->current = $match[2];
        $this->pos += strlen( $match[1]) + strlen( $match[2]) + strlen($match[3]);

        // We're trying to iterate past string
        if( $this->pos >= strlen($this->str)){
            $this->pos = -1;
        }

    }

    // Okay, we're done? :)
    function valid() {
        return ($this->pos > -1);
    }
}

And if you’ll use it on a bit more challenging string:

$a = new WordsIterator("Progress in Veterinary Science. And, make it !more! interesting!nWith new line.");
foreach( $a as $i){
    echo $i;
    echo "n";
}

Will you get the expected result:

Progress
in
Veterinary
Science
And
make
it
more
interesting
With
new
line

So you can easily use $i[0] to fetch first letter.You probably can see that this is more effective solution than splitting whole string into memory (always use only as little memory as possible). You also could easily modify this solution to work with continuous reading of files etc.

answered Apr 23, 2013 at 9:24

Vyktor's user avatar

VyktorVyktor

20.4k6 gold badges62 silver badges96 bronze badges

1

<?php $arr = explode(" ",$String);

foreach($arr as $s)
{
   echo substr($s,0,1);
}

?>

firstly I explode string by spaces then I substr first char.

http://php.net/substr

http://php.net/explode

Vyktor's user avatar

Vyktor

20.4k6 gold badges62 silver badges96 bronze badges

answered Apr 23, 2013 at 8:34

Robert's user avatar

RobertRobert

19.6k5 gold badges57 silver badges84 bronze badges

Try This

function initials($string) {
        if(!(empty($string))) {
            if(strpos($string, " ")) {
                $string = explode(" ", $string);
                $count = count($string);
                $new_string = '';
                for($i = 0; $i < $count; $i++) {
                $first_letter = substr(ucwords($string[$i]), 0, 1);
                $new_string .= $first_letter;
            }
            return $new_string;
            } else {
                $first_letter = substr(ucwords($string), 0, 1);
                $string = $first_letter;
                return $string;
            }
        } else {
            return "empty string!";
        }
    }
    echo initials('Thomas Edison');

answered May 27, 2013 at 4:06

San's user avatar

1

I like Reg Expression over any other method of string extraction, but if you are unfamiliar with Reg Ex then hear is a method using the explode() PHP function:

$string = "David Beckham";
$string_split = explode(" ", $string);
$inititals = $string_split[0][0] . $string_split[1][0];
echo $inititals;

Obviously the above code will only work on a name containing two words.

answered Jan 6, 2016 at 9:38

Matt Jameson's user avatar

This answer https://stackoverflow.com/a/33080232/1046909 but with multibyte strings support:

if (!function_exists('str_acronym')) {
    function str_acronym(string $str, int $min = -1, string $prefix = null): string
    {
        if (mb_strlen($str) <= $min) {
            return $str;
        };

        $words = explode(' ', $str);

        $acronym = strval($prefix);

        foreach ($words as $word) {
            if ($word = trim($word)) {
                $acronym .= mb_strtoupper(mb_substr($word, 0, 1));
            }
        }

        return $acronym;
    }
}

answered Aug 19, 2019 at 15:34

MingalevME's user avatar

MingalevMEMingalevME

1,7071 gold badge20 silver badges18 bronze badges

You can use that function based on the accepted answer from @Michael Berkowski

function buildAcronym($string, $length = 1) {
    $words = explode(" ", $string);
    $acronym = "";
    $length = (self::is_empty($string) || $length <= 0 ? 1 : $length);

    foreach ($words as $i => $w) {
        $i += 1;
        if($i <= $length) {
            $acronym .= $w[0];
        }
    }

    return $acronym;
}

The $length parameter determines how many chars you want to display

USAGE:

$acronym = buildAcronym("Hello World", 2);

answered May 11, 2020 at 20:33

J0rdAn's user avatar

J0rdAnJ0rdAn

1213 silver badges13 bronze badges

I’m a little underwhelmed by the suggested techniques here (despite having so many to choose from).

Assuming your input string is solely composed of whitespace delimited «words» (and you don’t need to validate that the first character of each word is an actual letter), you can use this concise, multibyte safe technique to trim all letters after the first letter from each word and also discard the delimiting whitespaces.

Code: (Demo)

$string = "Let's observe obviously knowledgeable approaches that target helpful items succinctly";

echo preg_replace('~SKS*s*~u', '', $string);

Output:

Lookatthis

If you want to specifically target «letters», you can use p{Ll} and non-letters with P{Ll} (as replacements for S and s. The K restarts the fullstring match — by effect, the matched first matched letter of each word is «set free» before matching more characters to be replaced by the empty string.


I see some other approaches on this page that are using lookbehinds to match the first letter of each word with preg_match_all('~(?<=s|b)pL~u', ...), but notice the effect on fringe cases:

$string = "Let's check some fringe-cases: like @mentions and email@example";
#matches:  ^   ^ ^     ^    ^      ^      ^     ^        ^   ^     ^

I cannot say if these would be desirable results, but if they were, then the pattern could be distilled to ~bpL~u because the word boundary (b) is a zero-length assertion that doesn’t require a lookbehind AND it covers every character that s could match.


I should also mention that any of the answers on this page that are accessing the first character by its offset (using array-like syntax like $word[0]) or substr() will fail whenever a multibyte character is encountered.

answered Apr 1, 2022 at 23:35

mickmackusa's user avatar

mickmackusamickmackusa

42.8k12 gold badges83 silver badges130 bronze badges

Try this

$string  = "Community College District";
echo $result = implode ('',array_map(function ($item) {return strtoupper($item[0]);} , explode(' ', $string)));

answered Jun 23, 2022 at 10:37

MD TAREK HOSSEN's user avatar

1

Понравилась статья? Поделить с друзьями:
  • What is the name of a microsoft excel file
  • What is the name manager in excel
  • What is the name box in excel
  • What is the moving average in excel
  • What is the most spoken english word