gpt4 book ai didi

php - 需要使用 str_replace 或任何其他方式翻译字符串中的单词

转载 作者:可可西里 更新时间:2023-10-31 23:12:41 25 4
gpt4 key购买 nike

我有一个包含英文字符的 XML 提要,我需要将其翻译成我的语言。问题是它不是翻译确切的字符串,而是翻译每个相似的词。

有没有办法只翻译完整的字符串而不是单词中的所有内容?

示例:

$string = "Red Cell is very good. Condition is new. But nobody buys it.";
$words = ["Red Cell", "Condition", "no", "Red", "new"];
$translations = ["Red Cell", "Stav", "ne", "Červený", "nový"];

$string = str_replace($words, $translations, $string);

我得到了什么:

Červený Cell 非常好。 Stav 是nevý。但没有人买账。


我想要的:

红细胞非常好。 Stav nový。但是没有人买账。


有什么方法可以翻译准确的字符串而不是所有包含该单词的内容?

最佳答案

我们的想法是构建一个关联数组 ($pairs),将单词作为键,将翻译作为值,然后构建一个包含所有单词的搜索模式:

$string = "Red Cell is very good. Condition is new. But nobody buys it.";
$words = ["Red Cell", "Condition", "no", "Red", "new"];
$translations = ["Red Cell", "Stav", "ne", "Červený", "nový"];

$pairs = array_combine($words, $translations);
krsort($pairs);

$pattern = '~\b(?:' . implode('|', array_keys($pairs)) . ')\b~u';

$result = preg_replace_callback($pattern, function ($m) use ($pairs) {
return $pairs[$m[0]];
}, $string);

echo $result;

demo

为确保首先测试最长的字符串(例如“Red Cell”和“Red”之间的字符串),模式中的单词以相反的顺序排序。

与使用数组的 str_replace 相比,具有单一模式和替换参数的 preg_replace_callback 的优势在于,当 str_replace 时,字符串仅被处理一次将每个单词解析一次整个字符串(它防止循环替换)。此外,由于搜索参数是正则表达式模式,您可以使用单词边界来确保单词不会在中间被截断。

关于php - 需要使用 str_replace 或任何其他方式翻译字符串中的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56948283/

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