PHP Lowercase String - Upper Case First Letter in Sentence

Another quick and easy one. Using ucfirst, strolower, and a few other functions. In this case my string is called $whyexp but you can change it to whatever you want just make sure you change of of them.

$whyexp = ucfirst(strtolower($whyexp));
$whyexp = preg_replace_callback('/[.!?].*?\w/', create_function('$matches', 'return strtoupper($matches[0]);'),$whyexp);
$whyexp = str_replace(" i "," I ", $whyexp);

The bottom line find’s all the letter I(‘s) and then converts them to upper case. Since the first line drops all the letters down to lower case, the second capitalizes all the first letters in the sentences, and the third cleans up all the lower case I(‘s) (if any…) to upper case.

Bare in mind if you have all abbrevaitions for something in the string that needs to be upper case add another line like the third one.

$whyexp = str_replace(" abs "," ABS ", $whyexp);

In this case I used ABS as an example. By adding that line, all the abbrevaitions for ABS are converted back to uppercase ABS. You can add as many lines as you need. You may also want to consider doing it in an array.

Post a Comment