任何人都可以帮我这么做吗?
例如我有一串
SOME of the STRINGS are in CAPITAL Letters
我想要的输出是
Some of the Strings are in Capital Letters
只有大写的人才会将他们的第一封信转为资本,其余的则为小写。
如何使用PHP实现这一目标?
提前致谢。
答案 0 :(得分:3)
您可以使用preg_replace_callback
查找所有大写单词,并使用自定义回调函数替换它们
答案 1 :(得分: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," ");
输出:
一些字符串在大写字母中
答案 2 :(得分:1)
您可以使用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
答案 3 :(得分: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;
答案 4 :(得分:0)
感谢您的回答,非常有帮助,它给了我一些想法。 我也使用preg_replace,只是分享给那些可能需要它的人。
preg_replace('/([A-Z])([A-Z ]+)/se', '"\\1" . strtolower("\\2")', $str);
OR
preg_replace('/([?!]{2})([?!]+)/', '\1', $str);