【问题标题】:Capitalize last letter of a string将字符串的最后一个字母大写
【发布时间】:2011-07-26 00:29:43
【问题描述】:

我怎样才能只大写字符串的最后一个字母。

例如:

hello

变成:

hellO

【问题讨论】:

  • 字符串?你的意思是一个段落/句子/单词?否则,您只是在您控制的字符串变量的最后一个位置上执行strtoupper()
  • echo strrev(ucfirst(strrev("hello"))); ;p
  • @karim79,这比我的想法好得多,您应该将其发布为答案。
  • @Brad - 完成。我意识到不管它看起来如何,它实际上可能是值得的。

标签: php capitalization


【解决方案1】:

复杂但有趣:

echo strrev(ucfirst(strrev("hello")));

演示:http://ideone.com/7QK5B

作为一个函数:

function uclast($str) {
    return strrev(ucfirst(strrev($str)));
}

【讨论】:

  • 效果很好!当我像这样输入它时,但我想做的是在wordpress中将页面标题更改为全部小写,最后一个字母大写。例如:现在标题显示为示例页面。我希望它显示为示例 pageE 。这是我尝试过的,但它不起作用code
  • @Kathy: $str = strtolower(the_title()); 然后。如果它不起作用,您的the_title() 函数中可能有错误。
  • 你会认为它会起作用。我不确定为什么不是。我会更改所有页面标题,以便在最后输入大写字母,但我不希望它在导航中以这种方式显示。我不确定如何进行缓存中断?该链接将我带到有关 AdSense 的内容。非常感谢您的帮助!
  • @Kathy - Bob 说的。对不起,我没有收到你的评论。只需先使用strtolower。谢谢@bob-the-destroyer。
  • 最好使用get_the_title() 来获得返回值。 the_title() 将回显。或者为返回值执行the_title('','', false);
【解决方案2】:

$s 是你的字符串时(Demo):

$s[-1] = strtoupper($s[-1]);

或者以函数的形式:

function uclast(string $s): string
{
  $s[-1] = strtoupper($s[-1]);
  return $s;
}

为了满足您的扩展需求,除了最后一个字符外,所有内容都必须小写:

function uclast(string $s): string
{
  if ("" === $s) {
    return $s;
  }

  $s = strtolower($s);
  $s[-1] = strtoupper($s[-1]);

  return $s;
}

【讨论】:

【解决方案3】:

这有两个部分。首先,您需要知道如何获取部分字符串。为此,您需要 substr() 函数。

接下来,有一个函数用于将字符串大写,称为strtotupper()

$thestring="Testing testing 3 2 1. aaaa";
echo substr($thestring, 0, strlen($thestring)-2) . strtoupper(substr($thestring, -1));

【讨论】:

    【解决方案4】:

    这是一个算法:

      1. Split the string s = xyz where x is the part of
         the string before the last letter, y is the last
         letter, and z is the part of the string that comes
         after the last letter.
      2. Compute y = Y, where Y is the upper-case equivalent
         of y.
      3. Emit S = xYz
    

    【讨论】:

      【解决方案5】:

      以下所有内容均可使用小写/大写/混合字符大小写

      <?php
          $word = "HELLO";
      
          //or
      
          $word = "hello";
      
          //or
      
          $word = "HeLLo";
      
          $word = strrev(ucfirst(strrev(strtolower($word))));
      
          echo $word;
      ?>
      

      所有单词的输出

      hellO
      

      【讨论】:

        【解决方案6】:
        $string = 'ana-nd';
        
        echo str_replace(substr($string, -3), strtoupper('_'.substr($string, -2)), $string);
        
        // Output: ana_ND
        
        
        $string = 'anand';
        
        echo str_replace(substr($string, -2), strtoupper(substr($string, -2)), $string);
        
        // Output: anaND
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-12-17
          • 2017-02-12
          • 1970-01-01
          • 1970-01-01
          • 2021-01-06
          • 2017-08-25
          • 2022-01-09
          • 1970-01-01
          相关资源
          最近更新 更多