Skip to content

Instantly share code, notes, and snippets.

@schlessera
Last active January 18, 2017 11:56
Show Gist options
  • Save schlessera/18770dc8d4641dbe9c76 to your computer and use it in GitHub Desktop.
Save schlessera/18770dc8d4641dbe9c76 to your computer and use it in GitHub Desktop.
Translatable string with multiple links that can be reordered and renamed
<?php
/**
* Translatable string with multiple links that can be reordered and renamed
* @author Alain Schlesser ([email protected])
*
* @see http://php.net/manual/function.preg-replace.php
* @see http://codex.wordpress.org/Function_Reference/_2
*/
// We use the preg_replace function to include placeholders inside the string to
// be translated. These placeholders can be reordered, just like a similar
// "sprintf('string with several %1$s that need to be %2$s', $links, $changed')"
// would allow you to do.
//
// The advantages:
// 1. Translators get more context and see the entire phrase.
// 2. Translators can change the anchor text, without needing to edit the url.
$translated_string = preg_replace(
// Array with regexp expressions that match your placeholders.
array(
'/1\{ *(.*?) *\}/',
'/2\{ *(.*?) *\}/',
'/3\{ *(.*?) *\}/',
),
// Array with the links. Note the $1 that gets replaced by the anchor text
// included in the translatable string.
array(
'<a href="http://example.com/products/" target="_blank">$1</a>',
'<a href="http://example.com/services/" target="_blank">$1</a>',
'<a href="http://example.com/contact/" target="_blank">$1</a>',
),
// Now comes the string itself. You can leave a note to the translators,
// explaining what the placeholders are all about
// TRANSLATORS: x{anchor-text} are placeholders that get replaced by
// corresponding links. Translate anchor text and reorder as necessary.
__(
'You can now buy our 1{Products} or order our 2{Premium Services}. '
. 'If unsure, do not hesitate to 3{contact us}.'
, 'example_plugin_textdomain'
)
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment