【问题标题】:How to make first and last letters capital in a word (therefore multiple strings) php如何使单词中的第一个和最后一个字母大写(因此多个字符串)php
【发布时间】:2016-07-28 14:34:48
【问题描述】:

我目前正在尝试完成的是将单词的第一个和最后一个字母大写。

目前这是我的功能:

function ManipulateStr($input){
    return strrev(ucwords(strrev($input)));
}

但是,这只会将每个单词的最后一个字母更改为大写,现在我正在努力思考如何将每个单词的第一个字母也大写。

一个例子:

输入:你好我的朋友

输出:你好,我的朋友们

也许我必须使用 substr?但是,如果我希望它适用于多个单词或单个单词,这将如何工作?

【问题讨论】:

  • return ucwords(strrev(ucwords(strrev($input))));
  • 你想要的输出请..
  • @FrayneKonok - 问题就在output: HellO MY FriendS
  • 非常感谢!我有一种感觉,我错过了一些小东西!
  • input: hello, my friEnds 应该生产什么?

标签: php string uppercase


【解决方案1】:

第一次使用strtolower 将字符串全部小写,然后使用函数ucwords 将第一个字符大写,然后再次使用strrev 并应用ucwords 将其他第一个字符大写。 然后最后使用strrev 获取第一个和最后一个字符大写的原始字符串。

更新功能

function ManipulateStr($input){
    return strrev(ucwords(strrev(ucwords(strtolower($input)))));
}

【讨论】:

    【解决方案2】:

    如果您正在寻找比 Frayne 提供的更快的功能(快约 20%),请尝试以下操作:

    function ManipulateStr($input)
    {
        return implode(
            ' ', // Re-join string with spaces
            array_map(
                function($v)
                {
                    // UC the first and last chars and concat onto middle of string
                    return strtoupper(substr($v, 0, 1)).
                           substr($v, 1, (strlen($v) - 2)).
                           strtoupper(substr($v, -1, 1));
                },
                // Split the input in spaces
                // Map to anonymous function for UC'ing each word
                explode(' ', $input)
            )
        );
    
        // If you want the middle part to be lower-case then use this
        return implode(
            ' ', // Re-join string with spaces
            array_map(
                function($v)
                {
                    // UC the first and last chars and concat onto LC'ed middle of string
                    return strtoupper(substr($v, 0, 1)).
                           strtolower(substr($v, 1, (strlen($v) - 2))).
                           strtoupper(substr($v, -1, 1));
                },
                // Split the input in spaces
                // Map to anonymous function for UC'ing each word
                explode(' ', $input)
            )
        );
    }
    

    【讨论】:

    • 我担心这会对带有标点符号的字符串给出不正确的结果。
    猜你喜欢
    • 2017-07-07
    • 2020-04-29
    • 2021-03-07
    • 2020-02-01
    • 2020-04-22
    • 2017-02-13
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多