PHP Code Function to TitleCase or Proper Case Sentences
PHP Code Function to Make the first letter of the first word of each sentence Title Case without changing or altering questions marks [?] exclamtion points [!] or periods [.]
Home
Short:
/* --------------------------------------------------------- Make the first letter of the first word of each sentence Title Case without changing or altering questions marks ? exclamtion points ! or periods . --------------------------------------------------------- */ function titleCaseSentence(string $value){ // split the sentences at [. ! ?] which are usually sentence ending marks $arr = preg_split('/([.?!]+)/', $value, -1, (PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE)); $newString = ""; // loop through each sentence foreach ($arr as $key => $sentence) { // if this $arr item is a sentence, Title case first word, otherwise its // a period or question mark or exclamation point so append with space after $data .= (($key & 1) == 0) ? ucfirst(trim($sentence)) : $sentence . " "; } return $data; }
source code home