得到每个单词的第一个字母 [英] get first letter of each word

查看:62
本文介绍了得到每个单词的第一个字母的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

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

推荐答案

explode() 上的空格,然后使用[]表示法将所得字符串作为数组访问:

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

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

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

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

例如,如果空格字符以外的字符(例如-,_)也要使用preg_split():

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

这篇关于得到每个单词的第一个字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆