Skip to content

Commit

Permalink
Work around temp strings being uppercased
Browse files Browse the repository at this point in the history
Handle Google Translate sometimes turning x0, x1 etc. into X0, X1 in the
translated string.
  • Loading branch information
q-- committed Jul 2, 2024
1 parent 43c4fa7 commit b7e0bc9
Showing 1 changed file with 5 additions and 7 deletions.
12 changes: 5 additions & 7 deletions src/Drivers/Translation.php
Original file line number Diff line number Diff line change
Expand Up @@ -87,21 +87,19 @@ public function getGoogleTranslate($language, $token)

// Step 2: Replace placeholders with temporary unique strings
$modifiedToken = $token;
$placeholderMap = [];
$tempStrings = [];
foreach ($placeholders as $index => $placeholder) {
$tempString = 'x' . $index;
$placeholderMap[$tempString] = $placeholder;
$modifiedToken = str_replace($placeholder, $tempString, $modifiedToken);
$tempStrings[] = 'x' . $index;
}
$modifiedToken = str_replace($placeholders, $tempStrings, $modifiedToken);

// Step 3: Translate the modified text using Google Translate
$tr = new GoogleTranslate($language, $this->sourceLanguage);
$translatedText = $tr->translate($modifiedToken);

// Step 4: Replace the temporary unique strings back with the original placeholders
foreach ($placeholderMap as $tempString => $placeholder) {
$translatedText = str_replace($tempString, $placeholder, $translatedText);
}
//Note: we're using case-insensitive replace because Google Translate sometimes uppercases the x
$translatedText = str_ireplace($tempStrings, $placeholders, $translatedText);

// Step 5: Check if the number of placeholders has stayed the same
preg_match_all($placeholderRegex, $translatedText, $translatedMatches);
Expand Down

0 comments on commit b7e0bc9

Please sign in to comment.