formatting a string with str_pad [duplicate]

2

With the help of the staff here in the stack, I've set up a function where I treat a string.

I'll post the code and explain the problem.

Function:

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);
}

Example, when I call the function like this:

echo mb_str_pad("ESPERANÇA", 15, "#");

It returns me:

ESPERANÇA######

Well the problem starts when you put a word that contains more than 15 letters, I need it to cut the word. Example of how to stay:

echo mb_str_pad("ESPERANÇAaaaaaaaaaaa", 15, "#");

It has to return like this:

ESPERANÇAaaaaaa

In other words, if he goes over 15 characters he has to cut and ignore everything on the right.

Can anyone help me with this?

    
asked by anonymous 14.09.2016 / 19:35

2 answers

0

Use strlen to get the size and substr to determine the beginning and end of the string

<?php

function mb_str_pad($input, $pad_length, $pad_string = ' ', $pad_type =    STR_PAD_RIGHT, $encoding = "UTF-8") {
$diff = strlen($input) - mb_strlen($input, $encoding);
$str = str_pad($input, $pad_length + $diff, $pad_string, $pad_type);
$tam = strlen ( $str );
return ($tam > 15 ) ? substr($str, 0, 15) : $str;
}

echo mb_str_pad("ESPERANÇAaaaaaaaaaaa", 15, "#");
?>
    
14.09.2016 / 19:43
4

Using the substr function, you pass three parameters: The string to be cut, the position of number of characters to be cut.

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 substr(str_pad($input, $pad_length + $diff, $pad_string, $pad_type),0,15);
}

echo mb_str_pad("ESPERANÇAaaaaaaaaaaa", 15, "#");

See working at ideone

    
14.09.2016 / 19:58