Everyone knows how to capitalize the first letter of a string ( ucfirst
) but what about the 2nd or Nth letter? I'm looking for a simple way to capitalize the character at position N of an ascii string.
I figured it out:
$str[$n] = strtoupper($str[$n]);
Note that the position is zero-based, so for the second character in a string $n = 1
.
With an ascii string you can do that:
$str[$n] = strtoupper($str[$n]);
But this doesn't work with an unicode string, it works only if characters are encoded with one byte.
For a multibyte string (utf8 for example) :
mb_internal_encoding ('UTF-8');
$str = mb_substr($str, 0, $n) . mb_strtoupper(mb_substr($str, $n, 1)) . mb_substr($str, ++$n);
This works for me for names like McDonald, McKinney, McCall, etc. Also, assumes there is only one instance of Mc in the string.
$newname = "Joe and Mary Mcdonald";
$position = stripos($newname, "Mc"); // case insensitive
$newname[$position + 2] = strtoupper($newname[$position + 2]);
echo $newname;
$str = "teststring";
$pos = 5;
function toUpper($str, $pos) {
return substr_replace($str, strtoupper(substr($str, ($pos-1), 1)), ($pos-1), 1) ;
}
echo toUpper($str, $pos);
I guess this is what you are looking for.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.