What are the potential pitfalls of using str_replace() when it comes to preserving the original case of the text being replaced?

When using str_replace() to replace text in a string, one potential pitfall is that the original case of the text being replaced may not be preserved. To solve this issue, you can use a combination of strpos() and substr_replace() functions to find the position of the text to be replaced and then replace it while maintaining the original case.

function replacePreserveCase($search, $replace, $subject) {
    $pos = strpos(strtolower($subject), strtolower($search));
    if ($pos !== false) {
        $before = substr($subject, 0, $pos);
        $after = substr($subject, $pos + strlen($search));
        $replace = substr_replace($subject, $replace, $pos, strlen($search));
        $replace = substr_replace($replace, $after, $pos + strlen($replace));
        return $replace;
    }
    return $subject;
}

$search = "example";
$replace = "replacement";
$subject = "This is an Example sentence.";
$result = replacePreserveCase($search, $replace, $subject);

echo $result; // Output: This is an Replacement sentence.