如何获得给定字符串的每个单词的首字母?
$string = "Community College District"; $result = "CCD";
我找到了javascript方法,但不确定如何将其转换为php。
explode()在空格上,然后使用[]表示法以数组形式访问结果字符串:
explode()
[]
$words = explode(" ", "Community College District"); $acronym = ""; foreach ($words as $w) { $acronym .= $w[0]; }
如果您期望多个空格可以分隔单词,请改用 preg_split()
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");