Q:

Replace character in word, but ignoring capitalisation?

I want to be able to replace a character in a word with a foreign accent character, and apply this to my entire Wordpress site, by adding an action to affect the_content, the_title and post_meta.
However, when using the below, although it works, it will swap the title case of the first letter if the word found begins with a capital, which I want to preserve.
Is there a way to just have one function to replace the character whilst preserving the other letters?
Or would it just be easier to have two functions, one for lowercase, and one for uppercase?
function bv_replace_tunbridge($content) {
    $content = str_replace('tunbridge', 't&ucirc;nbridge', $content);
    return $content;
}
add_filter('the_content','bv_replace_tunbridge');

A:

You could use preg_replace_callback to check if the u character is an uppercase or lowercase.
function bv_replace_tunbridge($content) {
    return preg_replace_callback('/t(u)nbridge/i', function ($match) {
        return str_replace(
            $match[1],
            $match[1] == 'u' ? '&ucirc;' : '&Ucirc;',
            $match[0]
        );
    }, $content);
}
add_filter('the_content','bv_replace_tunbridge');

Output
tunbridge // tûnbridge
TUNBRIDGE // TÛNBRIDGE
tUnbridge // tÛnbridge
Tunbridge // Tûnbridge

