如何只获得PHP中的大写首字母?

Bru*_*Vaz 1 php regex abbreviation preg-match-all

我想在缩写中转换短语,但不希望单词的每个第一个字母组成缩写,只需要大写的缩写.例如,我想将字符串"United States of America"转换为"USA"而不是"USOA",因为我发现的所有代码都有效.

在我的项目中,我必须显示类的时间表,并且一些类名称很像"LinguagemdeProgramaçãoOrientadaa Objeto"(面向对象的编程语言),如果我使用我在互联网上找到的代码,它将"LinguagemdeProgramaçãoOrientadaa Objeto"字符串转换为LDPOAO,而不是LPOO,因为它是有意义的.

我找到的代码:(它将一个字符串变成一个缩写,我想知道如何只选择输入$ result的大写字母)

$string = "Progress in Veterinary Science";

$expr = '/(?<=\s|^)[a-z]/i';
preg_match_all($expr, $string, $matches);

$result = implode('', $matches[0]);

$result = strtoupper($result);

echo $result;
Run Code Online (Sandbox Code Playgroud)

Jay*_*ard 5

这是代码.请注意正则表达式的更改:

$string = "Progress in Veterinary Science";

$expr = '/(?<=\s|^)[A-Z]/';
preg_match_all($expr, $string, $matches);    
$result = implode('', $matches[0]);
echo $result;
Run Code Online (Sandbox Code Playgroud)

  • 请养成[接受答案](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work)的习惯,帮助您解决问题@BrunoVaz (2认同)