Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/263.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将第一个字母转换为大写字母,但仅限于大写字符串-PHP_Php - Fatal编程技术网

将第一个字母转换为大写字母,但仅限于大写字符串-PHP

将第一个字母转换为大写字母,但仅限于大写字符串-PHP,php,Php,有人能帮我吗 例如,我有一个字符串 SOME of the STRINGS are in CAPITAL Letters 我想要输出的是 Some of the Strings are in Capital Letters 只有大写的才会将第一个字母改为大写,其余的则改为小写 如何使用PHP实现这一点 提前感谢。您可以使用preg\u replace\u callback查找所有大写单词并用自定义回调函数替换它们您可以使用strtolower和ucwords $word = "SOME of

有人能帮我吗

例如,我有一个字符串

SOME of the STRINGS are in CAPITAL Letters
我想要输出的是

Some of the Strings are in Capital Letters

只有大写的才会将第一个字母改为大写,其余的则改为小写

如何使用PHP实现这一点


提前感谢。

您可以使用
preg\u replace\u callback
查找所有大写单词并用自定义回调函数替换它们

您可以使用
strtolower
ucwords

$word = "SOME of the STRINGS are in CAPITAL Letters";
echo ucwords(strtolower($word));
输出

Some Of The Strings Are In Capital Letters
如果你想要你描述的那样

$word = "SOME of the STRINGS are in CAPITAL Letters";
$word = explode(" ", $word);
$word = array_map(function ($word) {return (ctype_upper($word)) ?  ucwords(strtolower($word)) : $word;}, $word);
echo implode(" ", $word);
输出

 Some of the Strings are in Capital Letters
快速示例:

$input = "SOME of the STRINGS are in CAPITAL Letters";
$words = explode(" ",$input);
$output = array();
foreach($words as $word)
{
    if (ctype_upper($word)) $output[] = $word[0].strtolower(substr($word,1));
    else $output[] = $word;
}
$output = implode($output," ");
输出:

有些字符串是大写的


谢谢你的回答,真的很有帮助,它给了我一些想法。 我也使用preg_replace,只是分享给那些可能需要它的人

preg_replace('/([A-Z])([A-Z ]+)/se', '"\\1" . strtolower("\\2")', $str);


如果要避免使用正则表达式

$text = "SOME of the STRINGS are in CAPITAL Letters";

$str_parts = explode(" ", $text);

foreach ($str_parts as $key => $str_part)
{
  if (ctype_upper($str_part) == strtolower(substr($str_part,1)))
  {
    $str_parts[$key] = ucfirst(strtolower($str_part));;
  }
}

$text = implode($str_parts, " ");

echo $text;

哦,cmon,你可以对正则表达式和字符串函数做一些研究,然后试一试。好的。stackoverflow是干什么的-_-不管怎样,谢谢你在一个你已经尝试解决的问题上得到帮助。很抱歉,我试过了,但我做不到,所以我寻求帮助。不要做一个好人,它不适合你:D。请研究一下“提问”按钮的作用。无论如何谢谢你,问题已经解决了。多亏了其他人。很抱歉,输出是“一些字符串是大写的”“只有大写的才会将第一个字母变成大写,其余的都是小写。”第二个看起来不错。但是你需要先映射小写的。无论如何,谢谢汉克斯。。添加了改进版本以输出“某些字符串为大写字母”注意:此函数删除现有的大写字母,例如,单词“字母”变为“字母”。
$text = "SOME of the STRINGS are in CAPITAL Letters";

$str_parts = explode(" ", $text);

foreach ($str_parts as $key => $str_part)
{
  if (ctype_upper($str_part) == strtolower(substr($str_part,1)))
  {
    $str_parts[$key] = ucfirst(strtolower($str_part));;
  }
}

$text = implode($str_parts, " ");

echo $text;