2

因此,我将一些句子插入到带有一些自动更正过程的数据库中。下面的句子:

$sentence = "Is this dog your's because it can't be mine";

以下代码将每个单词大写,但确保它不大写缩写(例如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 数据库中的是:

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

我不知道为什么会发生这种情况......我假设我在某个地方搞砸了。

4

2 回答 2

7

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

echo preg_replace_callback('/(?<=\s|^)[a-z]/', function($match) {
    return strtoupper($match[0]);
}, $sentence);

它通过使用后向断言确保每个小写字符前面都有一个空格(或句子的开头),然后再将其更改为大写。

于 2013-08-13T07:06:06.577 回答
3

您可能正在寻找ucwords代替(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"
于 2013-08-13T07:00:25.110 回答