对于给定的字符串,我如何获得每个单词的第一个字母?
$string = "Community College District";
$result = "CCD";
我找到了javascript方法,但不确定如何将其转换为php。
发布于 2012-03-15 00:58:34
在空格上使用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");
发布于 2013-04-23 16:34:38
假设单词都由空格分隔,这是一个合适的解决方案:
$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"
发布于 2013-04-23 16:49:35
有很多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);
https://stackoverflow.com/questions/9706429
复制相似问题