phpstringreplacecase-sensitive

Replace string and preserve original string's case in the replacement


I'm trying to do some sort of translator which would be able to keep text uppercase/lowercase.

Example:

Potato in the PLACE.
Potato in the pLAcE.
Potato in the place.
Potato in the Place.

I want to replace word place with garden while applying the original case in the replacement characters.

Potato in the GARDEN.
Potato in the gARdEn.
Potato in the garden.
Potato in the Garden.

It should also work with phrases.


Solution

  • So I managed to create my own function in the end. Thanks for help and inspiration though.

    function replaceWithCase($source, $replacement, $string, $pos = 0) {
    
        while (($pos = strpos(strtolower($string), strtolower($source), $pos))!== false) {
            $substr = mb_substr($string, $pos, strlen($source));
            $remaining = mb_substr($string, $pos + strlen($source));
    
            if (ctype_upper($substr)) {
                $string = substr_replace($string,strtoupper($replacement),$pos,strlen($source));
                continue;
            }
    
            $substrParts = preg_split('//u', $substr, null, PREG_SPLIT_NO_EMPTY);
            $replaceParts = preg_split('//u', $replacement, null, PREG_SPLIT_NO_EMPTY);
            $newWord = '';
    
            foreach ($replaceParts as $k => $rp) {
                if (array_key_exists($k,$substrParts))
                    $newWord .= ctype_upper($substrParts[$k]) ? mb_strtoupper($rp) : mb_strtolower($rp);
                else
                    $newWord .= $rp;  
            }
            $string = substr_replace($string,$newWord,$pos,strlen($source));
            $pos = $pos + strlen($source);
        }
    
        return $string;
    }
    
    echo replaceWithCase("place", "garden", "Potato is jumping all over the PLACE");
    echo "<br>";
    echo replaceWithCase("jumping", "running", "Potato is jumping all over the pLAcE");
    echo "<br>";
    echo replaceWithCase("jumping", "cry", "Potato is jumping all over the place");
    echo "<br>";
    echo replaceWithCase("all", "", "Potato is jumping all over the Place");
    echo "<br>";
    echo replaceWithCase(" ", ";", "Potato is jumping all over the Place", 10);
    echo "<br>";
    

    Output:

    Potato is jumping all over the GARDEN
    Potato is running all over the pLAcE
    Potato is cry all over the place
    Potato is jumping over the Place
    Potato is jumping;all;over;the;Place