如何仅将字符串的最后一个字母大写。
例如:
hello
变成:
hellO
复杂但有趣:
echo strrev(ucfirst(strrev("hello")));
演示:http: //ideone.com/7QK5B
作为一个函数:
function uclast($str) {
return strrev(ucfirst(strrev($str)));
}
$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;
}
这有两个部分。首先,您需要知道如何获取部分字符串。为此,您需要该substr()
功能。
接下来,有一个用于将字符串大写的函数,称为strtotupper()
.
$thestring="Testing testing 3 2 1. aaaa";
echo substr($thestring, 0, strlen($thestring)-2) . strtoupper(substr($thestring, -1));
这是一个算法:
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
可以使用以下所有内容的小写/大写/混合字符大小写
<?php
$word = "HELLO";
//or
$word = "hello";
//or
$word = "HeLLo";
$word = strrev(ucfirst(strrev(strtolower($word))));
echo $word;
?>
所有单词的输出
hellO
$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