Reputation: 1816
Anyone could help me doing this?
For example I have a string of
SOME of the STRINGS are in CAPITAL Letters
What I want exactly for the output is
Some of the Strings are in Capital Letters
Only those in UPPERCASE will be turn their first letter to capital and leave the rest as lower case.
How can I achieve this using PHP?
Thanks in advance.
Upvotes: 2
Views: 2189
Reputation: 4872
if you want to avoid regular expressions
$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;
Upvotes: 1
Reputation: 95103
You can use strtolower
and ucwords
$word = "SOME of the STRINGS are in CAPITAL Letters";
echo ucwords(strtolower($word));
Output
Some Of The Strings Are In Capital Letters
If you want it exactly the way you described
$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);
Output
Some of the Strings are in Capital Letters
Upvotes: 1
Reputation: 1816
Thanks for the answers, really helpful and it gives me ideas. I use preg_replace as well, just sharing to those who might need it too.
preg_replace('/([A-Z])([A-Z ]+)/se', '"\\1" . strtolower("\\2")', $str);
OR
preg_replace('/([?!]{2})([?!]+)/', '\1', $str);
Upvotes: 0
Reputation: 27073
Quick example:
$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," ");
Output:
Some of the Strings are in Capital Letters
Upvotes: 3
Reputation: 15629
you can use preg_replace_callback
to find all uppercase words an replace them with a custom callback function
Upvotes: 3