In PHP, sometimes we need to determine whether a string contains only uppercase letters, such as verifying if a filename complies with a rule that it should only include uppercase letters. The ctype_upper function is a very useful tool for checking if all characters in a string are uppercase letters.
This article will provide a detailed explanation of how to use the ctype_upper function for this purpose, with demonstrations based on actual filename scenarios.
ctype_upper is a PHP function that checks whether all characters in a string are uppercase letters. It returns true only if every character in the string is an uppercase letter (A-Z); otherwise, it returns false.
Function prototype:
bool ctype_upper(string $text)
The string to be checked is a filename.
The filename must only contain uppercase letters (A-Z); lowercase letters, numbers, special characters, etc., are not allowed.
If the filename meets the criteria, output a confirmation message; otherwise, output a warning message.
<?php
// Example filename
$filename = "DOCUMENT.TXT";
<p>// Extract the basename (without extension)<br>
$basename = pathinfo($filename, PATHINFO_FILENAME);</p>
<p>// Check if it contains only uppercase letters<br>
if (ctype_upper($basename)) {<br>
echo "The filename complies with the rule of containing only uppercase letters.";<br>
} else {<br>
echo "The filename does not comply; please ensure it contains only uppercase letters.";<br>
}<br>
?><br>
Here, the pathinfo function is used to extract the main part of the filename, avoiding any dots or lowercase letters in the extension from affecting the check. ctype_upper only verifies whether the basename is entirely uppercase letters.
ctype_upper only checks letters; it returns false if the string contains numbers, periods, underscores, or other characters.
If the filename includes an extension, you usually need to remove the extension before checking.
If the filename is an empty string, ctype_upper will return false.
Suppose a file is uploaded via a form, and the filename needs to comply with the uppercase-only rule. The example code is as follows:
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$filename = $_FILES['upload']['name'];
$basename = pathinfo($filename, PATHINFO_FILENAME);
echo "The uploaded filename complies with the rule.";
} else {
echo "The uploaded filename does not comply; please use only uppercase letters.";
}
}
?>