得到每个单词的第一个字母

时间:2012-03-14 16:56:00

标签: php string

如何获得给定字符串的每个单词的第一个字母?

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

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

25 个答案:

答案 0 :(得分:111)

对空格

explode(),然后使用[]表示法将结果字符串作为数组访问:

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

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

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

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

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

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

答案 1 :(得分:39)

实现这一目标的最佳方法是使用正则表达式。

让我们以合乎逻辑的方式分解你想要的东西:你希望字符串中的每个字符都在一个单词的开头。识别这些字符的最佳方法是查找以空格开头的那些字符。

所以我们从那个空格字符的lookbehind开始,然后是任何字符:

/(?<=\s)./

这将找到任何以空格开头的字符。但是 - 字符串中的第一个字符是字符串中的字符是您想要提取的字符。因为它是字符串中的第一个字符,所以它不能以空格开头。因此,我们希望匹配字符串中第一个字符前面的任何内容,因此我们添加start-of-subject assertion

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

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

所以我们最终得到:

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

但是我们如何在PHP中实际使用它?好吧,我们希望匹配字符串中正则表达式的所有次出现,以便我们使用(您猜对了)preg_match_all()

$string = "Progress in Veterinary Science";

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

现在我们拥有了我们想要提取的所有角色。要构建您显示的结果字符串,我们需要join them together again

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

...我们需要确保它们是all upper-case

$result = strtoupper($result);

这就是它的全部内容。

See it working

答案 2 :(得分:15)

假设这些单词都被空格分割,这是一个合适的解决方案:

$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"

答案 3 :(得分:7)

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

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

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

答案 4 :(得分:5)

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

答案 5 :(得分:5)

喜欢这个

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

答案 6 :(得分:5)

有很多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);

这是一个更强大和有用的功能,它支持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 = 'Leiðari í Kliniskum Útbúgvingum';
echo createAcronym($string);

答案 7 :(得分:4)

正如其他人所解释的那样,经典方法包括迭代初始字符串的每个单词,将单词缩小为第一个字母,并将这些首字母组合在一起。

这是一个结合不同步骤的辅助方法。

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

注意:如果给定的字符串为空,这将返回一个空字符串。

getInitials('Community College District')

  

字符串'CCD'(长度= 3)

getInitials()

  

string''(length = 0)

getInitials('Lorem ipsum dolor sic amet')

  

字符串'Lidsa'(长度= 5)

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

答案 8 :(得分:3)

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

// would output IaaS

答案 9 :(得分:2)

假设原始字符串正确构建(修剪且没有双空格),这就是我所做的:

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

基本上,将字符串分解为单词,提取单词的第一个字符并将其大写,然后将它们粘在一起。

答案 10 :(得分:2)

我做过的东西。

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

答案 11 :(得分:2)

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

答案 12 :(得分:1)

我认为你必须再次爆炸并加入他们......

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

答案 13 :(得分:1)

使用Prateeks基础,这是一个带解释的简单例子

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

答案 14 :(得分:1)

如果输入字符串中两个字母之间有更多的空格,请尝试这样做。

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

替代相同的代码

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

答案 15 :(得分:1)

这里有一个函数可以获取名称的首字母,如果首字母只有1个字母,那么它将返回名字的前2个字母。

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

答案 16 :(得分:0)

对于您将在大字符串(甚至直接来自文件)上执行此操作的情况,explode()不是执行此操作的最佳方法。想象一下,如果你必须将字符串2MB大量分成内存,会浪费多少内存。

只需更多编码和(假设为PHP >= 5.0),您就可以轻松实现PHP的Iterator类,它将完成此任务。这将接近python中的生成器和长话短说,这是代码:

/**
 * 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);
    }
}

如果你将它用在一个更具挑战性的字符串上:

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

你会得到预期的结果:

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

因此,您可以轻松地使用$i[0]来获取第一个字母。您可能会发现这比将整个字符串拆分为内存更有效(始终只使用尽可能少的内存)。您还可以轻松修改此解决方案,以便连续读取文件等。

答案 17 :(得分:0)

试试这个

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

答案 18 :(得分:0)

这样的事情可以解决问题:

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

答案 19 :(得分:0)

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

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

?>

首先我按空格分解字符串,然后我将第一个字符串作为字符。

http://php.net/substr

http://php.net/explode

答案 20 :(得分:0)

我喜欢Reg Expression而不是任何其他字符串提取方法,但是如果您不熟悉Reg Ex,那么使用explode() PHP函数听取的是一种方法:

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

显然,上面的代码只适用于包含两个单词的名称。

答案 21 :(得分:0)

试试这个 -

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

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

答案 22 :(得分:0)

为什么不使用str_word_count函数呢?

  1. 将每个单词排成一个数组
  2. reduce到第一个字母的数组

    $ acronym = array_reduce(     str_word_count(“社区大学区”,1),     函数($ res,$ w){         返回$ res。 $ w [0];     } );

答案 23 :(得分:0)

此答案https://stackoverflow.com/a/33080232/1046909,但支持多字节字符串:

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

答案 24 :(得分:0)

您可以根据@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;
}

$ length参数确定要显示的字符数

用法:

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