php sprintf() with foreign characters?

Mille picture Mille · Apr 14, 2013 · Viewed 12.3k times · Source

Seams to be like sprintf have a problem with foregin characters? Or is it me doing something wrong? Looks like it work when removing chars like åäö from the string though. Should that be necessary?

I want the following lines to be aligned correctly for a report:

2011-11-27   A1823    -Ref. Leif  -           12 873,00    18.98
2011-11-30   A1856    -Rättat xx -            6 594,00    19.18

I'm using sprintf() like this: %-12s %-8s -%-10s -%20s %8.2f

Using: php-5.3.23-nts-Win32-VC9-x86

Answer

Martin Prikryl picture Martin Prikryl · Apr 14, 2013

Strings in PHP are basically arrays of bytes (not characters). They cannot work natively with multibyte encodings (such as UTF-8).

For details see:
https://www.php.net/manual/en/language.types.string.php#language.types.string.details

Most string functions in PHP have multibyte equivalent though (with the mb_ prefix). But the sprintf does not.

There's a user comment (by "viktor at textalk dot com") with multibyte implementation of the sprintf on the function's documentation page at php.net. It may work for you:
https://www.php.net/manual/en/function.sprintf.php#89020