PHP Exercises: Convert the last 3 characters of a given string in upper case
PHP Basic Algorithm: Exercise-24 with Solution
Write a PHP program to convert the last 3 characters of a given string in upper case. If the length of the string has less than 3 then uppercase all the characters.
Sample Solution:
PHP Code :
<?php
// Define a function that modifies a string based on its length
function test($s)
{
// Check if the length of the string is less than 3
return strlen($s) < 3 ? strtoupper($s) : substr($s, 0, strlen($s) - 3) . strtoupper(substr($s, strlen($s) - 3));
}
// Test the function with different strings
echo test("Python") . "\n";
echo test("Javascript") . "\n";
echo test("js") . "\n";
echo test("PHP") . "\n";
?>
Explanation:
- Function Definition:
- The test function takes a single parameter $s, a string, and modifies it based on its length.
- String Modification Logic:
- If the length of $s is less than 3 characters:
- The entire string is converted to uppercase using strtoupper.
- If the length of $s is 3 characters or more:
- The last 3 characters are converted to uppercase.
- The modified string is created by concatenating the unaltered part of $s (up to strlen($s) - 3) with the uppercase version of the last 3 characters.
Output:
PytHON JavascrIPT JS PHP
Visual Presentation:
Flowchart:
PHP Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a PHP program to check if two given non-negative integers have the same last digit.
Next: Write a PHP program to create a new string which is n (non-negative integer) copies of a given string.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/php-exercises/basic-algorithm/php-basic-algorithm-exercise-24.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics