How to capitalise the first word of each sentence – PHP


So this can be a tricky one.  PHP has some excellent built-in functions for capitalising the first word of a string and capitalising all of the words in a string, but there are no built-in functions (that I’m aware of) that will capitalise the first word of each sentence.  This can be overcome using our old favourites, the regular expressions and preg_replace_callback() function.

$outputString = preg_replace_callback('/([.!?])\s*(\w)/', function ($matches) {
    return strtoupper($matches[1] . ' ' . $matches[2]);
}, ucfirst(strtolower($inputString)));


Share this post:
Related Posts
Getting the ID of draggable and droppable elements – jQuery
Count the number of days between two dates – PHP
  • Curtis
    Nov 23,2018 at 10:41 am

    Hey, thanks for the helpful post

  • Stephanie Fowell
    Sep 7,2018 at 4:49 pm

    Thank you for the great article

  • Karen T
    Aug 24,2018 at 5:10 pm

    I’ve been looking for this solution for an age, thank you!

    • Fluffy
      Aug 24,2018 at 7:20 pm

      No problem, glad it’s been useful 🙂

  • Kendall
    Aug 19,2018 at 7:56 am

    Thanks for the post

  • Matt
    Aug 15,2018 at 11:22 am

    Awesome, thanks dude

  • Katrin
    Jun 17,2018 at 8:08 am

    This is actually helpful, thanks.

    • Fluffy
      Jul 18,2018 at 6:35 am

      You’re welcome. Thanks for taking the time to comment 🙂

  • Simon
    Jun 10,2018 at 4:29 am

    Thanks to the great guide

    • Fluffy
      Jul 18,2018 at 6:34 am

      You’re welcome, glad you find it useful 🙂

Leave a Comment