用 preg_replace 大写单词的每个首字母 [英] Uppercase each first letter of words with preg_replace

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

问题描述

所以我将一些句子插入到具有一些自动更正过程的数据库中.下面这句话:

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 can't be mine";

以下代码将每个单词大写,但要确保它不大写缩写(例如 n't):

And the following code to capitalize each word but make sure it doesn't capitalize contractions (eg. n't):

str_replace(
    "'S", "'s", preg_replace(
       "/(\w+)n'T?/", "$1n't", (
           preg_replace(
              "/\b[a-z]/e", 
              'strtoupper("$0")', 
              ucwords($sentence)
           )
       )
   )
);

回显时,结果如下:

Is This Dog Your's Because It Can't Be Mine

这是我想要它做的,但是,它输入到我的 MySQL 数据库中的是:

This is what I want it to do, however, what it inputs into my MySQL database is:

Is This Dog Your's Because It Can'T Be Mine

我不知道为什么会这样......我假设我在某处搞砸了.

I have no idea why this is happening... I am assuming that I messed something up somewhere.

推荐答案

你当然应该使用 ucwords(),但这是您使用正则表达式的方式:

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

通过使用lookbehind 断言,在它变成大写之前.

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.

这篇关于用 preg_replace 大写单词的每个首字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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