php 获取每个单词的第一个字母

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9706429/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 07:27:35  来源:igfitidea点击:

get first letter of each word

phpstring

提问by Grigor

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.

我找到了 javascript 方法,但不确定如何将其转换为 php。

回答by Michael Berkowski

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

explode()在空格上,然后您使用[]符号来访问作为数组的结果字符串:

$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()

如果您期望多个空格可以分隔单词,请改为切换到 preg_split()

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

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

或者,如果除空格以外的字符分隔单词 ( -,_),也可以使用preg_split()

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

回答by DaveRandom

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 lookbehindfor 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 orthe 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 imodifier.

现在我们越来越近了。但是如果字符串包含多个空格的块呢?如果它包含一个空格后跟一个标点符号怎么办?我们可能不想匹配任何一个,在fat中我们可能只想匹配字母。我们可以用一个字符类来做到这一点[a-zA-Z]。我们可以使用i修饰符使表达式不区分大小写。

So we end up with:

所以我们最终得到:

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

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

但是我们如何在 PHP 中实际使用它呢?好吧,我们想匹配字符串中所有出现的正则表达式,所以我们使用(你猜对了)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

看到它工作

回答by casraf

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"

回答by Sverri M. Olsen

There are a lot of explodeanswers. I think using the strtokfunction is a much more elegant and memory-efficient solution:

有很多explode答案。我认为使用该strtok函数是一个更优雅和内存效率更高的解决方案:

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:

这是一个更强大和有用的函数,它支持 UTF8 字符和仅使用大写单词的选项:

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 = 'Leieari í Kliniskum útbúgvingum';
echo createAcronym($string);

回答by trejder

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

Michael Berkowski的(和其他人)的答案,简化为一行并正确处理多字节字符(即使用非拉丁字符串制作缩写/首字母):

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.

如果您正在处理非拉丁语、多字节字符串和字符,即在使用 UTF-8 编码字符串时,使用mb_substr($word, 0, 1, 'utf-8'), 而不是$word[0]似乎是必须的。

回答by Winston

Like this

像这样

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

回答by Ascherer

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

回答by Flo Schild

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

getInitials('Community College District')

string 'CCD' (length=3)

字符串“CCD”(长度=3)

getInitials()

getInitials()

string '' (length=0)

字符串''(长度=0)

getInitials('Lorem ipsum dolor sic amet')

getInitials('Lorem ipsum dolor sic amet')

string 'Lidsa' (length=5)

字符串 'Lidsa'(长度 = 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.

当然,您可以向 的回调函数添加过滤器array_reduce(),例如,strtoupper()如果您只喜欢大写首字母。

回答by Flo Schild

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

回答by billyonecan

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

// would output IaaS