本文介绍了获取字符串中每个单词的第一个字母的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何获取给定字符串的每个单词的第一个字母?
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");
这篇关于获取字符串中每个单词的第一个字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!