如何将句子中第一个单词的首字母大写?

Enk*_*kay 9 php regex user-input text-segmentation

我正在尝试编写一个函数来清理用户输入.

我并不想让它变得完美.我宁愿用小写的名字和首字母缩略词比用大写的完整段落.

我认为该函数应该使用正则表达式,但我很糟糕,我需要一些帮助.

如果下面的表达式后跟一个字母,我想把那个字母写成大写.

 "."
 ". " (followed by a space)
 "!"
 "! " (followed by a space)
 "?"
 "? " (followed by a space)
Run Code Online (Sandbox Code Playgroud)

更好的是,该功能可以在"."之后添加一个空格,"!" 和"?" 如果那些后面跟着一封信.

如何实现这一目标?

w35*_*l3y 33

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

由于修饰符e在PHP 5.5.0中已弃用:

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

  • 提醒一下,在PHP 5.5中不推荐使用e修饰符 (5认同)