Tag Archives: capitalise sentances

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:
read more