简体   繁体   中英

Making the first letter of every sentence upper case using ucfirst

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;

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

Yes. are you listening to me? huh?!"

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM