I would like to change a string in php from all upper case to normal cases. So that every sentence would start with an upper case and the rest would be in lower case.
Is there a simple way to do this ?
I would like to change a string in php from all upper case to normal cases. So that every sentence would start with an upper case and the rest would be in lower case.
Is there a simple way to do this ?
A simple way is to use strtolower to make the string lower case, and ucfirst to upper case the first char as follows:
$str=ucfirst(strtolower($str));
If the string contains multiple sentences, you'll have to write your own algorithm, e.g. explode on sentence separators and process each sentence in turn. As well as the first char, you might need some heuristics for words like "I" and any common proper nouns which appear in your text. E.g, something like this:
$sentences=explode('.', strtolower($str));
$str="";
$sep="";
foreach ($sentences as $sentence)
{
//upper case first char
$sentence=ucfirst(trim($sentence));
//now we do more heuristics, like turn i and i'm into I and I'm
$sentence=preg_replace('/i([\s\'])/', 'I$1', $sentence);
//append sentence to output
$str=$sep.$str;
$sep=". ";
}
I don't know of any method that will do this automatically. You would probably have to write your own with rules that would take of special cases like the letter 'i' needing to be capitalized when it is on its own. You would also still miss out on the ability to capitalize things like people and place names.
Perfectly possible
$s = "THIS IS THE LINE I'M GOING TO WORK ON";
$s = ucfirst(strtolower($s));
echo $s; //This is the line I'm going to work on
If the string contains only 1 sentence then you could use:
$string = ucfirst(strtolower($string));
Here's a function that will do it:
function sentence_case($s) {
$str = strtolower($s);
$cap = true;
for($x = 0; $x < strlen($str); $x++){
$letter = substr($str, $x, 1);
if($letter == "." || $letter == "!" || $letter == "?"){
$cap = true;
}elseif($letter != " " && $cap == true){
$letter = strtoupper($letter);
$cap = false;
}
$ret .= $letter;
}
return $ret;
}
Source:
Point to keep in mind: Do not apply this to all input fields!
People with ALL CAPS initials in their names can get mighty annoyed if you turn "Mike DF King" into "Mike Df King"
cheers :)
I am needing something similar to this but my situation is a bit different. I need to convert place names such as "BOCA RATON" to "Boca Raton" or LOS ANGELES" to "Los Angeles". If anyone can help please post or send me an email to webmaster (at) webdesignassociates.net