gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 13:32:08 25 4
gpt4 key购买 nike

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

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

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

最佳答案

explode()在空格上,然后使用适当的子字符串方法访问每个单词的第一个字符。

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

foreach ($words as $w) {
$acronym .= mb_substr($w, 0, 1);
}

如果您期望多个空格可以分隔单词,请改为使用 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");

关于php - 获取字符串中每个单词的第一个字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16164582/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com