Creating string in PHP

Asked

Viewed 348 times

4

It is possible to create a PHP variable of type string that contains so many bytes, that is, defined by the programmer?

Example in C:

char string[20];

In this case, string will always have 20 bytes, regardless of what is stored in it.


Resolution with str_pad(args):

$str = str_pad("HelloWorld", 20, "\0");

This line ensures that $str has 20 bytes, that is, if HelloWorld does not have 20 bytes, it fills with 0 the rest.

  • You want a new type or just make the string have a fixed amount of characters?

  • I want her to have a fixed amount of characters

  • In php you don’t have these things in C. It’s direct : $variavel = 'minha_string'. As I said in another answer: php is a weak typing language.

  • No, but you can make a 20-character substr that would be a solution

2 answers

6


If you just want to guarantee the size create and use a function that does this whenever you want to guarantee the size:

function fixedSTring($txt, $length) {
    $length = max($length, strlen($length);
    return str_pad(substr($txt, 0, $length), $length);
}

If you want something guaranteed and automatic, just create a new type, a new class that besides saving a string, keep her fixed size and apply the above criterion. Something like this (not complete and tested, it’s just a base)

final class FixedString {
    private $txt = '';
    public function __construct($txt, $length) {
        $length = max($length, strlen($length));
        $this->txt = str_pad(substr($txt, 0, $length), $length);
    }
    public function __toString() {
        return $this->txt;
    }
}

Use:

$texto = new FixedString("teste", 20);

I put in the Github for future reference.

Evidently you need to do better checks, have more methods that help the job. Making a new type should be very well thought out. I would not fill and cut the string automatically like this, you have better ways to deal with it, but the question doesn’t go into detail.

  • 1

    Okay. You gave me an idea. I’m going to do a report in git :)

  • @Wallacemaxters thanks for editing, can improve or make a class in your reply.

  • you can also put the substr in the __toString Overload to put __get and __set overloads to change the values

  • @Adirkuhn yes, it can improve a lot, but as I said, I only made a base, I did not intend to make the complete class.

  • Can implement ArrayAccess to access each part of the string as an index

  • 1

    @Wallacemaxters yes, there are several ways to optimize this. You can do the whole scheme of string completely and not using a string internal. Need to see if compensates.

  • Much appreciated, the function str_pad(args) solved my problem.

  • 1

    I really thought the problem was a lot simpler than it looked.

  • I get it, @bigown. The question is not "what can you do," but "what will he need"

  • avoid "non-binary safe" functions.. strlen() does not support multibyte and would return different values for multibyte characters. I suggest switching to mb_strlen() like any other function that does not support multibyte, you should switch to its equivalent of Mbstring functions.

  • I posted my resolution to the question, using the str_pad(args) function used by @bigown in his answer. If anything is missing, please correct me.

Show 6 more comments

3

PHP is a weak typing language. It is not possible to set an initial size for the string - at least not natively.

What you can do are functions or classes that will do this work.

Example:

function fixed_string($string, $length) {
    return substr(sprintf("%' {$length}s", $string), 0, $length);
}

var_dump(fixed_string('oi ', 20));

var_dump(fixed_string('oi oi oi oi oi oi oi oi oi', 20));

Upshot:

string '                 oi ' (length=20)

string 'oi oi oi oi oi oi oi' (length=20)

Updating

I created an enhanced class based on the @Maniero response.

See that in it I implement ArrayAccess and some features for identification of coding:

Fixedstring on Github

Example:

$string = new FixedString('Oi', 2, 'utf-8');
  • That’s not a trick

  • I’ll take the excerpt. These terms are sometimes appealing

  • 1

    This does not guarantee anything, it works if the person uses it well, IE, is gambiarra. Nothing against the answer, until I top it, mine is also Ambi in the first part. And the second is half-mouth.

  • @Wallacemaxters link to Fixedstring on Github is broken. Could you check? Thanks!

Browser other questions tagged

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