Uppercase each first letter of words with preg_replace

后端 未结 2 829
清酒与你
清酒与你 2021-01-22 15:16

So I have some sentences I am inserting into a database with some auto-correction processes. The following sentence:

$sentence = \"Is this dog your\'s because it         


        
2条回答
  •  礼貌的吻别
    2021-01-22 15:31

    You should of course use ucwords(), but this is how you would do it with a regular expression:

    echo preg_replace_callback('/(?<=\s|^)[a-z]/', function($match) {
        return strtoupper($match[0]);
    }, $sentence);
    

    It makes sure that each lower case character is preceded by a space (or start of the sentence) by using a lookbehind assertion, before it's changed to upper case.

提交回复
热议问题