formatting a string with str_pad

Asked

Viewed 125 times

2

Guys with the help of the stack people here, I set up a function where I do the processing of 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 so:

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

She returns to me:

ESPERANÇA######

Well, the problem starts when you put in a word that contains more than 15 letters, I need her to cut the word. Example of what it should look like:

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

You have to return like this:

ESPERANÇAaaaaaa

In other words, if you pass 15 characters, you have to cut and ignore everything on the right.

Can someone help me with that?

2 answers

4

Using the function replace, you pass three parameters: The string to be cut, the start position and the amount of characters to 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 on ideone

0


Uses strlen to take the size and substr to determine the start 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, "#");
?>

  • Well that way it almost worked, but I need to capture the value that I pass when I call the function mb_str_pad for in every place I call her, he possesses a different value.

  • blz put it like this substr($str, 0, $pad_length);

  • Well, I’m glad I helped in some way. :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.