【问题标题】:How to make ucwords ignore words in all caps? [closed]如何让 ucwords 忽略所有大写的单词? [关闭]
【发布时间】:2013-12-28 04:49:27
【问题描述】:

我有一些文本需要每个首字母大写。但是有些词全部大写,我希望这些词被忽略。

$foo = 'product manufacturer for CAMERON TRAILERS';
$foo = ucwords($foo); 

我需要这个输出如下:

Product Manufacturer For CAMERON TRAILERS.

这可能吗?

【问题讨论】:

标签: php


【解决方案1】:

再想一想,因为ucfirstucwords 都没有将大写字符转换为小写字符; ucwords 对于这种情况应该没问题。我更改了下面的函数,使其更加规范,这取决于您如何解释问题。


您需要定义自己的函数来执行此操作; PHP 在其标准库中没有具有这种行为的函数(参见上面的注释)。

// Let's create a function, so we can reuse the logic
function sentence_case($str){
    // Let's split our string into an array of words
    $words = explode(' ', $str);
    foreach($words as &$word){
        // Let's check if the word is uppercase; if so, ignore it
        if($word == strtoupper($word)){
            continue;
        }
        // Otherwise, let's make the first character uppercase
        $word = ucfirst(strtolower($word));
    }
    // Join the individual words back into a string
    return implode(' ', $words);
}

echo sentence_case('product manufacturer for CAMERON TRAILERS');
// "Product Manufacturer For CAMERON TRAILERS"

【讨论】:

  • 效果很好。非常感谢你。感谢大家的帮助和耐心。
【解决方案2】:

当你期望这样的时候使用这个代码Product Manufacturer For Cameron Trailers

$foo = 'product manufacturer for CAMERON TRAILERS';
echo $foo = ucwords(strtolower($foo));

看这里http://www.php.net/manual/pt_BR/function.ucwords.php。 ucwords 不翻译大写单词

<?php
$foo = 'hello world!';
$foo = ucwords($foo);             // Hello World!

$bar = 'HELLO WORLD!';
$bar = ucwords($bar);             // HELLO WORLD!
$bar = ucwords(strtolower($bar)); // Hello World!
?>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-03
    • 1970-01-01
    • 2021-01-27
    • 1970-01-01
    • 1970-01-01
    • 2022-08-20
    相关资源
    最近更新 更多