Php 需要使用str_replace或任何其他方式翻译字符串中的单词
我有一个带有英文字符的XML提要,需要翻译成我的语言。问题在于它不是转换精确的字符串,而是转换每个相似的单词 有没有办法只翻译完整的字符串而不翻译单词内部的所有内容 例如:Php 需要使用str_replace或任何其他方式翻译字符串中的单词,php,regex,preg-replace,str-replace,Php,Regex,Preg Replace,Str Replace,我有一个带有英文字符的XML提要,需要翻译成我的语言。问题在于它不是转换精确的字符串,而是转换每个相似的单词 有没有办法只翻译完整的字符串而不翻译单词内部的所有内容 例如: $string = "Red Cell is very good. Condition is new. But nobody buys it."; $words = ["Red Cell", "Condition", "no", "Red", "new"]; $translations = ["Red Cell", "Sta
$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是11月。但是没有人买它
有没有办法翻译精确的字符串,而不是所有包含该单词的内容?我们的想法是构建一个关联数组(
$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;
为了确保首先测试最长的字符串(例如“Red Cell”和“Red”),模式中的单词按相反顺序排序
与使用数组的
str\u replace
相比,使用单个模式和替换参数的preg\u replace\u callback
的优势在于,当str\u replace
将每个字解析整个字符串一次时,字符串仅处理一次(它防止循环替换)。此外,由于搜索参数是正则表达式,所以可以使用Word边界来确定中间没有一个单词。请注意这一点,谢谢您的帮助和回答。无论如何我发现了一个问题,但我无法解决它。我很乐意得到任何提示。当涉及到翻译像“电子书阅读器电池”这样的常规句子时,没有问题。但现在我遇到了将“充电器|交流适配器”翻译成“|”或逻辑的情况。我需要正则表达式模式来忽略管道并获取整个字符串。我试着在管道前面加上“\”。但它不起作用。我还尝试了这个“充电器[\\\\124;]交流适配器”,但它给了我“注意:未定义的索引:在C:\xampp\htdocs\test\robbie.php的第147行”错误。谢谢你的帮助help@SophiaTibbers:构建模式时,将array_key($pairs)
更改为array_映射(函数($i){return preg_quote($i,~');},array_key($pairs))
preg_quote
将转义regex特殊字符,如管道。不要在$words
数组中转义这些字符,因为匹配的字符串不会转义。您是最好的先生。非常感谢。