Home > Article > Backend Development > How to convert some characters to uppercase in PHP as required
There is a similar article before "How does PHP convert the last few characters of a specified string to uppercase and the rest remains unchanged". This article introduces how PHP converts the last few characters of a specified string to uppercase. Convert to uppercase and leave the rest unchanged, then the topic of this article is to convert some characters to uppercase as required.
First let's take a look at the specific requirement description of the problem:
"Write a PHP program to convert the last 3 characters of a given string to uppercase. If the length of the string is less than 3 , capitalize all characters".
Based on the above requirements, do you have any ideas for implementation?
I will upload the code directly below, please give me a reference:
The PHP code is as follows:
<?php function test($s) { return strlen($s) < 3 ? strtoupper($s) : substr($s, 0, strlen($s) - 3).strtoupper(substr($s, strlen($s) - 3)); } echo test("PHP")."<br>"; echo test("Javascript")."<br>"; echo test("js")."<br>"; echo test("Python")."<br>";
The output result is:
PHP JavascrIPT JS PytHON
Note:
strtoupper() function: used to convert strings to uppercase. (This function is binary safe.)
strlen() function: used to return the length of a string. (If successful, the length of the string is returned, if the string is empty, 0 is returned.)
substr() function: used to return a part of the string. (Returns the extracted part of the string, returns FALSE on failure, or returns an empty string.)
Ternary operator
Another conditional operator is the "?:" (or ternary) operator.
Syntax format:
(expr1) ? (expr2) : (expr3)
The value when expr1 evaluates to TRUE is expr2, and when expr1 evaluates to FALSE, the value is expr3.
Since PHP 5.3, the middle part of the ternary operator can be omitted. The expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE and expr3 otherwise.
Related recommendations: "PHP's ternary operator"
Finally, I would like to recommend the latest and most comprehensive "PHP video tutorial 》~Come and learn!
The above is the detailed content of How to convert some characters to uppercase in PHP as required. For more information, please follow other related articles on the PHP Chinese website!