gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 06:01:37 25 4
gpt4 key购买 nike

我正在尝试做某种能够保持文本大写/小写的翻译器。我也需要在 PHP 字符串和 MySQL 查询中替换它。

例子:

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.

我想用“花园”替换单词“地方”。

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.

它也应该适用于短语。

最佳答案

我创建了一个函数来为您替换单词并保留大小写。

function replaceWithCase($source, $replacement, $string) {
// Does the string contain the source word?
if (strpos($string, $source) === false) {
return false;
}

// If everything is uppercase, return the replacement fully uppercase
if (ctype_upper($source)) {
return str_replace($source, strtoupper($replacement));
}

// Set an array to work with
$characters = array();

// Split the source into characters
$sourceParts = explode('', $source);

// Loop throug the characters and set the case
foreach ($sourceParts as $k => $sp) {
if (ctype_upper($sp)) {
$characters[$k] = true;
} else {
$characters[$k] = false;
}
}

// Split the replacement into characters
$replacementParts = explode('', $replacement);

// Loop through characters and compare their case type
foreach ($replacementParts as $k => $rp) {
if (array_key_exists($k, $characters) && $characters[$k] === true) {
$newWord[] = strtoupper($rp);
} else {
$newWord[] = strtolower($rp);
}
}

return substr_replace($source, implode('', $newWord), $string);
}

// usage
echo replaceWithCase('AppLes', 'bananas', 'Comparing AppLes to pears');

注意:它未经测试,可能需要一些调整

关于php - 如何用另一个字符串替换字符串并在 php 和 mysql 中保持大小写?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44450192/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com