What are some alternative methods to str_ireplace for replacing characters in a text while maintaining case sensitivity?

The issue with using str_ireplace is that it is case-insensitive, meaning it will replace characters regardless of their case. To maintain case sensitivity when replacing characters in a text, you can use a combination of functions like preg_replace_callback and strtoupper/lowercase functions to achieve the desired result.

$text = "Hello World!";
$replace = "o";
$new_text = preg_replace_callback('/[oO]/', function($match) {
    return strtoupper($match[0]) === $match[0] ? strtoupper($replace) : strtolower($replace);
}, $text);

echo $new_text; // Outputs "HellO WOrld!"