Cap Sentence
It’s odd sometimes the code that comes one when your tired:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | function sentenceCap($str){ $alphanumeric = "/[a-zA-Z0-9]/"; $period = "/\./"; $count = strlen($str); $newString = $str[0]; for($i = 1; $i < $count; $i++){ $curr = $str[$i]; if (preg_match($period, $curr)){ $nextCap = true; } if(preg_match($alphanumeric, $curr)){ if (!$nextCap){ $curr = strtolower($curr); }else{ $nextCap = false; } } $newString .= $curr; } return $newString; } |
5 minutes on php.net… no luck… skrew it… 5 minutes of coding this absurd function. At least I can replace the implementation in the morning when I think of a better way to do it.
EDIT:
I didn’t have time to clean up the function yet but Evan Frohlich posted this really nice solution:
1 2 3 4 5 6 7 8 9 | function sentenceCap($str){ return preg_replace('/([.!?])\s*(\w)/e', "strtoupper('\\1 \\2')", ucfirst(strtolower($str))); } //Also regarding the above I think you should shift all of your strings //to Upper Case first. Otherwise un-capitalized words that begin a sentence will not be corrected. //Line 4 should be: $curr = strtoupper($str[$i]); |
