Stichoza / google-translate-php

🔤 Free Google Translate API PHP Package. Translates totally free of charge.
MIT License
1.79k stars 380 forks source link

feat (translation): add ability to ignore keys in translations #199

Closed kylemilloy closed 8 months ago

kylemilloy commented 8 months ago

What does this change?

Allows us to provide keys to translate without eating them up, for example, Hello :name was becoming Bonjour :nom. Now this will stored as Bonjour :name still.

How does this work?

We do a couple preg_replace commands to extract replacements, modify the string before sending to Google, and then swap back in our replacements. In a string such as Hello :name are you :type_of_greeting? for example this replaces this string with Hello ${0} are you ${1}? with the ${\d} values being ignored by Google, everything around it gets translated. When we receive this translated string back we then swap these values out for the matching keys that should be there so it changes from Bonjour ${0} are you ${1} to Bonjour :name are you :type_of_greeting? where our system can then translate it as normal.

Notes

Resolves #198

Also introduces ambiguous space characters being introduced by Google Translate (see screenshot).

image

image

kylemilloy commented 8 months ago

@Stichoza

I've gone ahead and responded to your feedback. I have it so it always runs through the key extraction but it's ignored if you don't set it explicitly as requested. Tests are expanded to show a couple examples of this and one for custom key matching (like if you wanna do {{key}} for example).

You can also set this off of the static method or constructor too for ease of use...

// like this...
$translator = new GoogleTranslate(pattern: '/:(\w+/');

// or this...
GoogleTranslate::trans(pattern: '/:(\w+/');

// or this
$translator->preserveParameters('/:(\w+/');

If patterns like :name and :key are the default I have it so you can just call $translator->preserveParameters() and it will do that for you, or you can customize it as above. In the constructor we pass null here instead to turn it off by default.