Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
mb_str_pad
<?php
/**
* mb_str_pad
*
* @param string $input
* @param int $pad_length
* @param string $pad_string
* @param int $pad_type
* @return string
* @author Kari "Haprog" Sderholm
*/
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 );
}
@naitsirch

This comment has been minimized.

Copy link

naitsirch commented Sep 27, 2012

There is a feature request in the PHP bug tracker for integrating such a function in the core. Please look at https://bugs.php.net/bug.php?id=21317 and vote for it. Thanks

If you want to provide explicit encoding usage, you can define the function like this:

function mb_str_pad($input, $pad_length, $pad_string = ' ', $pad_type = STR_PAD_RIGHT, $encoding = null)
{
    if (!$encoding) {
        $diff = strlen($input) - mb_strlen($input);
    }
    else {
        $diff = strlen($input) - mb_strlen($input, $encoding);
    }
    return str_pad($input, $pad_length + $diff, $pad_string, $pad_type);
}
@jsebrech

This comment has been minimized.

Copy link

jsebrech commented Dec 25, 2012

If your pad_string is itself multibyte, this still won't give the right result. The tricky part is that str_pad will copy as many bytes out of the pad_string as it needs to reach the pad_length, and will therefore generate corrupt strings. So, basically, you cannot use str_pad unless you first make sure you append too many bytes and then copy the right length out of it via mb_substr.

@Lewiscowles1986

This comment has been minimized.

Copy link

Lewiscowles1986 commented Feb 18, 2015

bad idea as unless the whole string is multi-byte this could lead to issues with string encoding...

@trialforce

This comment has been minimized.

Copy link

trialforce commented Dec 15, 2016

Works for me.

@ksidibe

This comment has been minimized.

Copy link

ksidibe commented Mar 13, 2017

Works for me too...
This is the behavior I expected from str_pad.

@rquadling

This comment has been minimized.

Copy link

rquadling commented Oct 7, 2019

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.