Uppercase each first letter of words with preg_replace

后端 未结 2 830
清酒与你
清酒与你 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.

    0 讨论(0)
  • 2021-01-22 15:39

    You are probably looking for ucwords instead (Demo):

    $sentence = "Is this dog your's because it can't be mine";
    
    echo ucwords($sentence); # Prints "Is This Dog Your's Because It Can't Be Mine"
    
    0 讨论(0)
提交回复
热议问题