Hi, I have an exercise in PHP where $letra
I assign the letter 'm' to the variable, I pass that variable as a parameter to a function to convert it to uppercase through its ASCII code
Code:
<?php
echo "<h2>Letra minuscula a mayuscula</h2>";
$letra = "m";
echo "La letra minuscula es: ".$letra."<br>";
echo "Pasando la letra minuscula a la funcion...<br><br>";
function minusToMayus($letra)
{
$letra = chr(77);
return $letra;
}
$letra = minusToMayus($letra);
echo "La letra minuscula se a convertido mayuscula: ".$letra;
?>
I can't use the function strtoupper()
, what I need is to make another function that validates that the variable $letra
is really lowercase, then convert it to uppercase, otherwise display a message saying that the letter is already in uppercase.
Thanks in advance.
If you look at the ASCII table, the uppercase letters are always 32 integers below the lowercase letters, this means that obtaining the ASCII code of your lowercase letter, in this case "m" (ASCII code: 109), you subtract 32 and you obtain the "M" (ASCII code: 77).
Note: ord() function gives you the ASCII value of a character, on the contrary, chr() function gives you the character by passing it an ASCII code.
I leave you another possibility to convert a letter to uppercase with the function
range()
andstr_replace()
, including a function which checks if the letter was already capitalized withctype_upper()
:Ver Demo Online
BONUSES:
Now if someone told you I want it to convert accented letters as well and you can't use
mb_strtoupper()
, then you can usemb_convert_case()
.And to check if the letter is uppercase we use the regular expression
/\p{Lu}/u
which checks for Unicode characters :Ver Demo Online