How to apply str_pad correctly to a string that has asentos

1

I have this situation, I am applying the function

  

str_pad

to fill a text string with spaces, but the problem is when the string contains accents (accents or ñ), since it tells me that character as if they were two, which causes the string to be filled with a minus character . Example

$texto="niña";
echo str_pad($texto,7,"-");

Output obtained:

  

"girl -"

Desired output:

  

"girl ---"

I do not know if there is an easy way to fix this, or you have to do it manually.

    
asked by jn901113jn 07.09.2018 в 18:56
source

2 answers

2

It is a bug of PHP, the developers made their function so that it works what you propose, I leave you the league and an example. Bug str_pad

<?php

function mb_str_pad( $texto, $longitud, $relleno = '', $tipo_pad = STR_PAD_RIGHT, $codificacion = null  ){
    $diff = empty( $codificacion ) ? ( strlen( $texto ) - mb_strlen( $texto )) : ( strlen( $texto ) - mb_strlen( $texto, $codificacion ) );
    return str_pad( $texto, ($longitud + $diff), $relleno, $tipo_pad ); 
}

$arr = array( 'laptop', 'ñu', 'niña', 'computadora', 'silicón', 'gato' );

foreach( $arr as $a ){
    echo mb_str_pad( $a, 7, '-' ) . '<br>';
}

?>
    
answered by 07.09.2018 в 19:44
0

I found in the php documentation , this solution is a bit long but works perfectly.

function str_pad_unicode($str, $pad_len, $pad_str = ' ', $dir = STR_PAD_RIGHT) {
    $str_len = mb_strlen($str);
    $pad_str_len = mb_strlen($pad_str);
    if (!$str_len && ($dir == STR_PAD_RIGHT || $dir == STR_PAD_LEFT)) {
        $str_len = 1; // @debug
    }
    if (!$pad_len || !$pad_str_len || $pad_len <= $str_len) {
        return $str;
    }

    $result = null;
    $repeat = ceil($str_len - $pad_str_len + $pad_len);
    if ($dir == STR_PAD_RIGHT) {
        $result = $str . str_repeat($pad_str, $repeat);
        $result = mb_substr($result, 0, $pad_len);
    } else if ($dir == STR_PAD_LEFT) {
        $result = str_repeat($pad_str, $repeat) . $str;
        $result = mb_substr($result, -$pad_len);
    } else if ($dir == STR_PAD_BOTH) {
        $length = ($pad_len - $str_len) / 2;
        $repeat = ceil($length / $pad_str_len);
        $result = mb_substr(str_repeat($pad_str, $repeat), 0, floor($length))
                    . $str
                       . mb_substr(str_repeat($pad_str, $repeat), 0, ceil($length));
    }

    return $result;
}
    
answered by 07.09.2018 в 20:04