phpregexuser-inputtext-segmentation

How to capitalize first letter of first word in a sentence?


I am trying to write a function to clean up user input.

I am not trying to make it perfect. I would rather have a few names and acronyms in lowercase than a full paragraph in uppercase.

I think the function should use regular expressions but I'm pretty bad with those and I need some help.

If the following expressions are followed by a letter, I want to make that letter uppercase.

 "."
 ". " (followed by a space)
 "!"
 "! " (followed by a space)
 "?"
 "? " (followed by a space)

Even better, the function could add a space after ".", "!" and "?" if those are followed by a letter.

How this can be achieved?


Solution

  • $output = preg_replace('/([.!?])\s*(\w)/e', "strtoupper('\\1 \\2')", ucfirst(strtolower($input)));
    

    Since the modifier e is deprecated in PHP 5.5.0:

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