Reputation: 3774
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 ?
Upvotes: 2
Views: 3839
Reputation: 300845
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=". ";
}
Upvotes: 10
Reputation: 26583
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 :)
Upvotes: 0
Reputation: 5917
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:
http://codesnippets.joyent.com/posts/show/715
Upvotes: 3
Reputation: 7854
If the string contains only 1 sentence then you could use:
$string = ucfirst(strtolower($string));
Upvotes: 1
Reputation: 14529
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
Upvotes: 1
Reputation: 37885
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.
Upvotes: 2