Special characters throwing off str_pad in php?

前端 未结 3 821
半阙折子戏
半阙折子戏 2020-12-16 19:26

I\'m writing a module that is supposed to be able to export transaction records in BankOne format.

Here is the specification of the format

Here is an example

相关标签:
3条回答
  • 2020-12-16 20:16
    function mb_str_pad($input, $pad_length, $pad_string = ' ', $pad_type = STR_PAD_RIGHT) {
        $diff = strlen($input) - mb_strlen($input,mb_detect_encoding($input));
        return str_pad($input, $pad_length + $diff, $pad_string, $pad_type);
    }
    
    0 讨论(0)
  • 2020-12-16 20:23

    This is happening because 'Ã' is a multi-byte character (4 bytes long), and str_pad is counting bytes rather than logical characters.

    This is why you are missing three spaces, str_pad is counting 'Ã' as 4 single byte characters instead of one multi-byte one.

    Try this function (credit here).

    <?
    function mb_str_pad( $input, $pad_length, $pad_string = ' ', $pad_type = STR_PAD_RIGHT)
    {
        $diff = strlen( $input ) - mb_strlen( $input );
        return str_pad( $input, $pad_length + $diff, $pad_string, $pad_type );
    }
    ?>
    
    0 讨论(0)
  • 2020-12-16 20:23

    Using Gordon's solution you just have to add the encoding type to the mb_strlen and it will count the bytes correctly (at least it worked for me)

    Here is the function I used:

    function mb_str_pad( $input, $pad_length, $pad_string = ' ', $pad_type = STR_PAD_RIGHT, $encoding="UTF-8") {
        $diff = strlen( $input ) - mb_strlen($input, $encoding);
        return str_pad( $input, $pad_length + $diff, $pad_string, $pad_type );
    }
    

    Credit for the idea here

    0 讨论(0)
提交回复
热议问题