将字符串的最后一个字母大写

6

如何将字符串的最后一个字母大写。

例如:

hello

成为:

hellO

字符串?你是指段落/句子/单词吗?否则,你只是在一个由你控制的字符串变量的最后位置执行strtoupper()函数。 - Jared Farrish
4
echo strrev(ucfirst(strrev("hello"))); ;pecho strrev(ucfirst(strrev("hello"))); ;p - karim79
@karim79,这比我的想法好多了,你应该把它发布为答案。 - Brad
@Brad - 完成了。我意识到尽管它看起来很不起眼,但实际上它可能是值得的。 - karim79
6个回答

14

有点复杂但很有趣:

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

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

作为一个函数:

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

1
@Kathy:首先执行 $str = strtolower(the_title());。如果不行,那么你的 the_title() 函数可能存在错误。 - bob-the-destroyer
是的,你会认为它应该能够工作。我不确定为什么它不行。我想将所有页面标题更改为以大写字母结尾输入,但是我不希望它在导航中显示为那样。我不知道如何进行缓存打破?那个链接带我去了关于广告的东西。非常感谢你的帮助! - Kathy
@Kathy - 照Bob所说。抱歉,我没看懂你的评论。先使用 strtolower。谢谢 @bob-the-destroyer。 - karim79
2
最好使用 get_the_title() 来获取返回值。the_title() 会直接输出。或者使用 the_title('','', false); 来获取返回值。 - hakre
@bob-the-destroyer - 我认为那是WordPress术语。 - karim79
显示剩余4条评论

3

$s是您的字符串时(演示):

$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;
}

@Martijn:https://3v4l.org/15aT3 在8.0.0-8.0.9版本中看起来很好。自从7.1.0版本以来,有了-1优化,我应该更新答案:https://3v4l.org/9Lj4c - hakre

1
这个有两个部分。首先,你需要知道如何获取字符串的部分。为此,你需要使用substr()函数。
接下来,还有一个用于将字符串转换为大写的函数,称为strtotupper()
$thestring="Testing testing 3 2 1. aaaa";
echo substr($thestring, 0, strlen($thestring)-2) . strtoupper(substr($thestring, -1));

0
$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

0
这是一个算法:
  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

0

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

<?php
    $word = "HELLO";

    //or

    $word = "hello";

    //or

    $word = "HeLLo";

    $word = strrev(ucfirst(strrev(strtolower($word))));

    echo $word;
?>

输出所有单词

hellO

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接