Php 获取字符串中每个单词的第一个字母

Php 获取字符串中每个单词的第一个字母,php,string,Php,String,如何获取给定字符串中每个单词的第一个字母 $string = "Community College District"; $result = "CCD"; 我找到了javascript方法,但不确定如何将其转换为php。在空格上,然后使用[]符号作为数组访问结果字符串: $words = explode(" ", "Community College District"); $acronym = ""; foreach ($words as $w) { $acronym .= $w[0]

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

$string = "Community College District";
$result = "CCD";
我找到了javascript方法,但不确定如何将其转换为php。

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

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

foreach ($words as $w) {
  $acronym .= $w[0];
}
如果您希望多个空格可以分隔单词,请切换到
preg\u split()

或者,例如,如果空格以外的字符分隔单词(
-,
),也可以使用
preg\u split()

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

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

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

首先,我用空格分解字符串,然后再替换第一个字符


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

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

像这样的事情应该可以做到:

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

我认为你必须爆发,再次加入他们

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

像这样

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

preg_match_all('#)(?有很多
explode
答案。我认为使用
strtok
函数是一个更优雅、更节省内存的解决方案:

$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"
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);
这是一个更强大、更有用的函数,它支持UTF8字符和仅使用大写单词的选项:

/(?<=\s)./

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

让我们以逻辑的方式分解您想要的内容:您希望字符串中的每个字符都位于单词的开头。识别这些字符的最佳方法是查找前面有空格的字符

因此,我们从一个空格字符开始,后跟任意字符:

/(?<=\s|^)./
但是我们实际上如何在PHP中使用它呢?我们希望匹配字符串中所有出现的正则表达式,所以我们使用(您猜对了):

…我们需要确保他们:

这就是一切


对于在大字符串(甚至直接从文件)上执行此操作的情况,这并不是最好的方法。想象一下,如果必须将2MB大字符串拆分为内存,会浪费多少内存

只需稍加编码(假设
PHP>=5.0
),您就可以轻松实现PHP的类,从而实现这一点。这将接近python中的generator,长话短说,代码如下:

/**
*用于从字符串中连续读取单词的类。
*/
类WordsIterator实现迭代器{
私人$pos=0;
私人$str='';
私人$index=0;
private$current=null;
//Regexp解释说:
//([^\\w]*?)-在实际单词字符之前吃掉所有非单词字符
//仅当字符串具有非单词字符时才使用
//([\\w]+)-Word
//([^\\w]+?|$)-尾部鞭打
private$re='([^\\w]*?)([\\w]+)([^\\w]+?|$)~imsS';
//主初始化字符串
公共函数构造($str){
$this->str=$str;
}
//重新开始索引
函数倒带(){
$this->pos=0;
$this->index=0;
$this->current=null;
}
//获取当前单词
函数电流(){
返回$this->current;
}
//返回当前所在单词的id(也可以使用偏移量)
函数键(){
返回$this->index;
}
//这里是魔术表演的地方
函数next(){
如果($this->pos<0){
返回;
}
$match=array();
++$this->index;
//如果我们找不到任何其他匹配的零件…将位置设置为-1
//和停止功能
如果(!preg_match($this->re,$this->str,$match,0,$this->pos)){
$this->current=null;
$this->pos=-1;
返回;
}
//跳过我们现在读到的内容
$this->current=$match[2];
$this->pos+=strlen($match[1])+strlen($match[2])+strlen($match[3]);
//我们正在尝试迭代过去的字符串
如果($this->pos>=strlen($this->str)){
$this->pos=-1;
}
}
//好了,我们结束了吗?:)
函数valid(){
退货($this->pos>-1);
}
}
如果您将其用于更具挑战性的字符串:

$a=new-WordsIterator(“兽医科学的进步。还有,让它更有趣吧!”);
foreach($a作为$i){
echo$i;
回音“\n”;
}
你会得到预期的结果吗:

进展
在里面
兽医
科学类
及
制作
信息技术
更多
有趣的
具有
新的
线
因此,您可以轻松地使用
$i[0]
提取第一个字母。您可能会发现,这是一种比将整个字符串拆分到内存(始终使用尽可能少的内存)更有效的解决方案。您还可以轻松地修改此解决方案,以处理文件的连续读取等。

尝试此方法

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

// would output IaaS
函数首字母($string){
如果(!(空($string))){
if(strpos($string,“”){
$string=分解(“,$string);
$count=count($string);
$new_字符串=“”;
对于($i=0;$i<$count;$i++){
$first_letter=substr(ucwords($string[$i]),0,1);
$new\u string.=$first\u字母;
}
返回$new_字符串;
}否则{
$first_letter=substr(ucwords($string),0,1);
$string=$first_字母;
返回$string;
}
}否则{
返回“空字符串!”;
}
}
回音首字母(“托马斯·爱迪生”);

<代码> > p>使用PrAtEdEclipse基金会,这里有一个简单的例子,解释< /P>
foreach(explode(' ', $words) as $word) $acronym .= mb_substr($word, 0, 1, 'utf-8');
Michael Berkowski(和其他人)的答案,简化为一行,正确处理多字节字符(即用非拉丁字符串制作缩写/首字母):


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

我编造的东西

$string = "David Beckham";
$string_split = explode(" ", $string);
$inititals = $string_split[0][0] . $string_split[1][0];
echo $inititals;
/**
/(?<=\s|^)[a-z]/i
$string = "Progress in Veterinary Science";

$expr = '/(?<=\s|^)[a-z]/i';
preg_match_all($expr, $string, $matches);
$result = implode('', $matches[0]);
$result = strtoupper($result);
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');
$str = 'I am a String!';
echo implode('', array_map(function($v) { return $v[0]; }, explode(' ', $str)));

// would output IaaS
//  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'
foreach(explode(' ', $words) as $word) $acronym .= mb_substr($word, 0, 1, 'utf-8');
/**
 * 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;
}
$string = "David Beckham";
$string_split = explode(" ", $string);
$inititals = $string_split[0][0] . $string_split[1][0];
echo $inititals;
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);
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);
/**
 * @return string
 */
function getInitials($string = null) {
    return array_reduce(
        explode(' ', $string),
        function ($initials, $word) {
            return sprintf('%s%s', $initials, substr($word, 0, 1));
        },
        ''
    );
}
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);
}
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;
}
$acronym = buildAcronym("Hello World", 2);
$name = 'John Doe';
$initials = implode( '', array_map( function ( $part ) { 
    return strtoupper( $part['0'] );
}, explode( ' ', $name ) ) );