How can I capitalize only the last letter of a string.
For example:
hello
becomes:
hellO
If you just want the last letter of the last word, str. capitalize() is the way to go.
To capitalize the first character of a string, We can use the charAt() to separate the first character and then use the toUpperCase() function to capitalize it. Now, we would get the remaining characters of the string using the slice() function.
Performing the . upper() method on a string converts all of the characters to uppercase, whereas the lower() method converts all of the characters to lowercase.
Python String capitalize() Method Syntax Return: The capitalize() function returns a string with the first character in the capital.
Convoluted but fun:
echo strrev(ucfirst(strrev("hello")));
Demo: http://ideone.com/7QK5B
as a function:
function uclast($str) {
return strrev(ucfirst(strrev($str)));
}
When $s
is your string (Demo):
$s[-1] = strtoupper($s[-1]);
Or in form of a function:
function uclast(string $s): string
{
$s[-1] = strtoupper($s[-1]);
return $s;
}
And for your extended needs to have everything lower-case except the last character explicitly upper-case:
function uclast(string $s): string
{
if ("" === $s) {
return $s;
}
$s = strtolower($s);
$s[-1] = strtoupper($s[-1]);
return $s;
}
There are two parts to this. First, you need to know how to get parts of strings. For that, you need the substr()
function.
Next, there is a function for capitalizing a string called strtotupper()
.
$thestring="Testing testing 3 2 1. aaaa";
echo substr($thestring, 0, strlen($thestring)-2) . strtoupper(substr($thestring, -1));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With