php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #38437 substr() - slightly change its contract
Submitted: 2006-08-12 20:34 UTC Modified: 2016-01-15 17:56 UTC
Votes:1
Avg. Score:5.0 ± 0.0
Reproduced:0 of 1 (0.0%)
From: zizka at seznam dot cz Assigned: nikic (profile)
Status: Closed Package: *General Issues
PHP Version: 5.1.4 OS:
Private report: No CVE-ID: None
 [2006-08-12 20:34 UTC] zizka at seznam dot cz
Description:
------------
string substr ( string string, int start [, int length] )

Currently:
If string is less than *or equal* to start characters long, FALSE will be returned.

I suggest:
If string is less than start characters long, FALSE will be returned.

The latter is more "ideologically clean". See the behavior of analogical methods in Java, JavaScript, C, etc. E.g. I did some simple parser, where the string of the form $<anything> is expected. I wanted to get <anything>, so I did:

if($s !== '' && $s[0] == '$')
  $s2 = substr($s, 1);

Then, behaved by Java's String.substring(), I wrote:

if($s2 === '')
  // Replace $s2 with some default value;

After several minutes of searching for the bug, I noticed the fact mentioned above.

Reproduce code:
---------------
substr("Ahoj", 4);

Expected result:
----------------
An empty string.

Actual result:
--------------
FALSE.

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2010-06-22 04:10 UTC] salsi at icosaedro dot it
The manual states that "If length is given and is 0, FALSE or NULL an empty string will be returned.". This is not true, as substring($s, $start, $length) seems to behave in a very unpredictable way with NULL string, empty string and at the string boundaries when $length==0:

var_dump( substr("a", 0, 0) ); # => "", ok
var_dump( substr("a", 1, 0) ); # => FALSE rather than ""

var_dump( substr("", 0, 0) );  # => FALSE rather than ""

var_dump( substr(NULL, 0, 0) ); # => FALSE rather than ""

In my opinion, substr() should always return a string, possibly empty, of length $length bytes provided that 0 <= $start and $start + $length <= strlen($s). And then an empty string should be returned when $length==0.

If $start is negative, the value $start = strlen($s) - $start should be considered and the algorithm above applied.

The NULL value should be considered as the empty string "" as in PHP tradition.
 [2016-01-15 17:56 UTC] nikic@php.net
-Status: Open +Status: Closed -Package: Feature/Change Request +Package: *General Issues -Assigned To: +Assigned To: nikic
 [2016-01-15 17:56 UTC] nikic@php.net
This has been implemented in PHP 7.0.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Fri Mar 29 12:01:27 2024 UTC