update page now
PHP 8.1.34 Released!

Voting

: max(zero, zero)?
(Example: nine)

The Note You're Voting On

nospam at nospam dot com
8 years ago
Improved method of capitalizing first characters of sentences.
The first two manipulations (double spaces & all caps) are optional so can be removed without harm.

<?php
// return string with first letters of sentences capitalized
function ucsentence($str) {
  if ($str) { // input
    $str = preg_replace('/'.chr(32).chr(32).'+/', chr(32), $str); // recursively replaces all double spaces with a space
    if (($x = substr($str, 0, 10)) && ($x == strtoupper($x))) $str = strtolower($str); // sample of first 10 chars is ALLCAPS so convert $str to lowercase; if always done then any proper capitals would be lost
    $na = array('. ', '! ', '? '); // punctuation needles
    foreach ($na as $n) { // each punctuation needle
      if (strpos($str, $n) !== false) { // punctuation needle found
        $sa = explode($n, $str); // split
        foreach ($sa as $s) $ca[] = ucfirst($s); // capitalize
        $str = implode($n, $ca); // replace $str with rebuilt version
        unset($ca); //  clear for next loop
      }
    }
    return ucfirst(trim($str)); // capitalize first letter in case no punctuation needles found
  }
}
?>

"heLLo EarthLing!" >> "HeLLo EarthLing!"
"I'M MOSTLY. caps!  " >> "I'm mostly. Caps!"
"ALLCAPS" >> "Allcaps"
"i haVe neST.ed punct,u.ation!  sp    A  c es.  and CAPs..  " >> "I haVe neST.ed punct,u.ation! Sp A c es. And CAPs.."

<< Back to user notes page

To Top