Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Str_pad not working

Tags:

php

    **PHP**

    $datearr = explode("/", $cutOff);
    $month = $datearr[0];
    $day = $datearr[1];
    $year = $datearr[2];
    $mainten = "MAINTENANCE";
    $pad=' ';
    $maint = str_pad($mainten, 20, $pad);
    $string = $cduid . $maint . $inarea . $year . $month . $day . "\n";

I am trying to parse this string to a server and $maint has to be padded with spaces to the right. I have also tried.....

    $datearr = explode("/", $cutOff);
    $month = $datearr[0];
    $day = $datearr[1];
    $year = $datearr[2];
    $mainten = "MAINTENANCE";
    $maint = str_pad($mainten, 20);
    $string = $cduid . $maint . $inarea . $year . $month . $day . "\n";

When I echo $string $maint only has 1 space on the right. If I replace $pad=' '; with $pad='.'; I get the correct result but I need for it to be spaces.

What am I missing here?

like image 490
Erich Niemand Avatar asked Oct 23 '13 09:10

Erich Niemand


People also ask

What is Str_pad function in PHP?

The str_pad() function is a built-in function in PHP and is used to pad a string to a given length. We can pad the input string by any other string up to a specified length. If we do not pass the other string to the str_pad() function then the input string will be padded by spaces.

Which of the following function pads one string with another in PHP?

The str_pad() function pads a string to a new length.


2 Answers

In HTML you can have only one space shown, but normally in source there are count of spaces, as you wish.

&nbps; will not work with str_pad, because it has 6 characters (in HTML its only 1 character), but for str_pad it will fail.

There is only one way, how to do it, you have to pad some character (ie. ~) and then replace it with  

$maint = str_replace('~', ' ', str_pad($mainten, 20, '~')); // just use some character you know isn't in your string

This will 100% work.

like image 98
Legionar Avatar answered Nov 05 '22 19:11

Legionar


When I echo $string $maint only has 1 space on the right.

The problem is that if you echo your string in HTML code, it will not show all the spaces. If you view source of that page you can see all the spaces added.

like image 30
eis Avatar answered Nov 05 '22 19:11

eis