如何用另一个字符串替换字符串并在php和mysql中保持大小写? [英] How to replace string with another string and keep case in php and mysql?

查看:46
本文介绍了如何用另一个字符串替换字符串并在php和mysql中保持大小写?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试做某种能够保持文本大写/小写的翻译器.我也需要在 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.

示例:

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.

它也适用于短语.

推荐答案

所以我最终设法创建了自己的函数.感谢您的帮助和启发.

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>";

输出:

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

这篇关于如何用另一个字符串替换字符串并在php和mysql中保持大小写?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆