如何将句子中第一个单词的首字母大写? [英] How to capitalize first letter of first word in a sentence?

查看:288
本文介绍了如何将句子中第一个单词的首字母大写?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这如何实现?

推荐答案

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

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

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)));

这篇关于如何将句子中第一个单词的首字母大写?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆