How can I capitalize only the last letter of a string.
For example:
hello
becomes:
hellO
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));
Here's an algorithm:
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
Lowercase / uppercase / mixed character case for everything following can be used
<?php
$word = "HELLO";
//or
$word = "hello";
//or
$word = "HeLLo";
$word = strrev(ucfirst(strrev(strtolower($word))));
echo $word;
?>
Output for all words
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
精彩评论