0

I'm trying to make the first letter of every sentence to be upper case while keeping the punctuation marks. I have tried ucfirst, but it only makes the first letter of the string uppercase, and not every other sentences. How do I fix this?

$text = "yes. are you listening to me? huh?!"
$text = ucfirst($text);

echo $text;

Expected Output:

Yes. Are you listening to me? Huh?!"

Actual Output:

Yes. are you listening to me? huh?!"
jessica
  • 1,667
  • 1
  • 17
  • 35

1 Answers1

2

Try this:

function ucfirstSentence($str){
     $str = ucfirst(strtolower($str));
     $str = preg_replace_callback('/([.!?])\s*(\w)/', 
       create_function('$matches', 'return strtoupper($matches[0]);'), $str);
     return $str;
}
Ngô Văn Thao
  • 3,671
  • 1
  • 20
  • 24