dongshuo2752 2017-06-09 05:51
浏览 111
已采纳

如何用另一个字符串替换字符串并在php和mysql中保留大小写?

I'm trying to do some sort of translator which would be able to keep text uppercase/lowercase. I need to replace it in PHP string and MySQL query too.

Example:

Potato is jumping all over the PLACE.
Potato is jumping all over the pLAcE. (optional)
Potato is jumping all over the place.
Potato is jumping all over the Place.

I want to replace word 'place' with 'garden'.

Potato is jumping all over the GARDEN.
Potato is jumping all over the gARdEe. (optional)
Potato is jumping all over the garden.
Potato is jumping all over the Garden.

It should also work with phrases.

  • 写回答

4条回答 默认 最新

  • dongtan7639 2017-06-12 11:07
    关注

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?