2

任何人都可以帮我这样做吗?

例如我有一串

SOME of the STRINGS are in CAPITAL Letters

我想要的输出是

Some of the Strings are in Capital Letters

只有大写字母的首字母大写,其余字母小写。

如何使用 PHP 实现这一点?

提前致谢。

4

5 回答 5

3

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

于 2012-09-28T13:18:13.167 回答
3

快速示例:

$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," ");

输出:

一些字符串是大写字母

于 2012-09-28T13:26:59.460 回答
1

您可以使用strtolowerucwords

$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
于 2012-09-28T13:25:22.660 回答
1

如果你想避免正则表达式

$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;
于 2012-09-28T13:34:46.223 回答
0

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

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

或者

preg_replace('/([?!]{2})([?!]+)/', '\1', $str);
于 2012-09-28T13:33:00.830 回答