Hello Internals,

Is there any particular reason why the substr() function doesn't accept a
null $length like mb_substr() does?  It seems the behavior to read through
the end of the string can only be controlled by the presence or absence of
the $length parameter:  https://3v4l.org/YpuO1

I discovered this discrepancy between the two methods while attempting to
create a specialized string wrapper class with a method like this:

    public function getSubstring(int $start, ?int $length = null): string
    {
        if ($this->isMultibyte) {
            return mb_substr($this->line, $start, $length, $this->encoding);
        } else {
            return substr($this->line, $start, $length);
        }
    }

This method would not work as expected without additional boilerplate like:

    public function getSubstring (int $start, ?int $length = null): string
    {
        if ($this->isMultibyte) {
            return mb_substr($this->line, $start, $length, $this->encoding);
        } elseif ($length === null) {
            return substr($this->line, $start);
        } else {
            return substr($this->line, $start, $length);
        }
    }

Or:

    public function getSubstring (int $start, ?int $length = null): string
    {
        if ($this->isMultibyte) {
            return mb_substr($this->line, $start, $length, $this->encoding);
        } else {
            return substr($this->line, $start, $length ??
(strlen($this->line) - $start));
        }
    }

Are there any historical reasons preventing substr() from accepting a null
$length like mb_substr() does?  I'd be happy to write the RFC and take a
stab at the implementation if there's interest in such a change.

Regards,

Colin O'Dell
colinod...@gmail.com

Reply via email to