How do you reverse the case of characters in a string in php with example?

Hello Friends Today, through this tutorial, I will tell you How do you reverse the case of characters in a string in PHP With Example? To reverse the case of characters in a string in PHP, you can use the `strrev()` function along with `strtolower()` and `strtoupper()` functions to handle the case reversal. Here’s how you can do it:

<?php

// Function to reverse the case of characters in a string
function reverseCase($str) {

// Reverse the string
$reversedStr = strrev($str);

// Loop through each character and reverse the case
$result = '';
for ($i = 0; $i < strlen($reversedStr); $i++) {
$char = $reversedStr[$i];
if (ctype_lower($char)) {
$result .= strtoupper($char);
} elseif (ctype_upper($char)) {
$result .= strtolower($char);
} else {
$result .= $char; // Preserve non-alphabetic characters
}
}
return $result;
}

// Example string
$string = "Hello World 123";

// Reverse the case of characters in the string
$reversedString = reverseCase($string);

// Output the original and reversed strings
echo "Original string: $string <br>";
echo "Reversed case string: $reversedString";

?>

In this example:

1. We define a function `reverseCase()` which takes a string as input.
2. Inside the function, we first reverse the string using `strrev()`.
3. Then, we loop through each character of the reversed string, using `ctype_lower()` and `ctype_upper()` functions to determine whether the character is lowercase or uppercase.
4. For each character, we reverse its case using `strtolower()` and `strtoupper()` functions accordingly.
5. Non-alphabetic characters are preserved as is.
6. The function returns the string with reversed case characters.

Output:

Original string: Hello World 123 
Reversed case string: 321 dlroW OLLEh

As you can see, the case of characters in the string has been reversed. Uppercase letters have become lowercase, and lowercase letters have become uppercase, while non-alphabetic characters remain unchanged.