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

前端 未结 7 829
猫巷女王i
猫巷女王i 2020-11-27 20:43

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 par

相关标签:
7条回答
  • 2020-11-27 20:55
    $Tasks=["monday"=>"maths","tuesday"=>"physics","wednesday"=>"chemistry"];
    
    foreach($Tasks as $task=>$subject){
    
         echo "<b>".ucwords($task)."</b> : ".ucwords($subject)."<br/>";
    }
    
    0 讨论(0)
  • 2020-11-27 20:57
    $output = preg_replace('/([\.!\?]\s?\w)/e', "strtoupper('$1')", $input)
    
    0 讨论(0)
  • 2020-11-27 20:58

    Separate string into arrays using ./!/? as delimeter. Loop through each string and use ucfirst(strtolower($currentString)), and then join them again into one string.

    0 讨论(0)
  • 2020-11-27 20:58

    How about this? Without Regex.

    $letters = array(
    'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
     'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'
    );
    foreach ($letters as $letter) {
        $string = str_replace('. ' . $letter, '. ' . ucwords($letter), $string);
        $string = str_replace('? ' . $letter, '? ' . ucwords($letter), $string);
        $string = str_replace('! ' . $letter, '! ' . ucwords($letter), $string);
    }
    

    Worked fine for me.

    0 讨论(0)
  • 2020-11-27 20:59

    This:

    <?
    $text = "abc. def! ghi? jkl.\n";
    print $text;
    $text = preg_replace("/([.!?]\s*\w)/e", "strtoupper('$1')", $text);
    print $text;
    ?>
    
    Output:
    abc. def! ghi? jkl.
    abc. Def! Ghi? Jkl.
    

    Note that you do not have to escape .!? inside [].

    0 讨论(0)
  • 2020-11-27 21:11
    $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)));
    
    0 讨论(0)
提交回复
热议问题