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

Need to translate words in string by using str_replace or any other way

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

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

示例:

$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ý。但是 ne很多人买账。


我想要什么:

红细胞很好。 Stavnový。但是没人买。


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

我们的想法是构建一个关联数组 ($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" 之间),模式中的单词按相反的顺序排序。

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