Search code examples
phpgettext

msgmerge: `invalid control sequence` when printing a price with a dollar sign


I'd like to print, for example, $10, where the number is stored in a variable, and I also want to be able to localize the string around the price.

This is my code:

__("I understand I will be charged \${$cost} for listing this item.");

This prints:

I understand I will be charged $10 for listing this item.

If I don't use \$ before the variable, I get, the following, without the dollar sign or the cost:

I understand I will be charged for listing this item.

Ok, that's fine.

Except that when I run msgmerge to generate localization files for translation purposes, it complains: invalid control sequence

It seems to not like the "\$" part, because it passes when I remove it. But I'm not sure what to do to appease msgmerge AND get the cost to print properly.


Solution

  • I'm afraid that's not how gettext is meant to be used. The calls to internationalisation functions in your PHP source code need to have static string literals. Otherwise, helper tools like msgmerge cannot see the texts because they don't execute PHP, they just read the source.

    The usual approach is something like:

    // Print to stdout
    printf(_('I understand I will be charged $%s for listing this item.'), $cost);
    

    ... or:

    // Save to a variable
    $string = sprintf(_('I understand I will be charged $%s for listing this item.'), $cost);