|  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
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
View Add Comment Developer Edit
Anyone can comment on a bug. Have a simpler test case? Does it work for you on a different platform? Let us know!
Just going to say 'Me too!'? Don't clutter the database with that please !
Your email address:
Solve the problem:
23 - 22 = ?
Subscribe to this entry?

 [2006-08-12 20:34 UTC] zizka at seznam dot cz
string substr ( string string, int start [, int length] )

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:


Add a Patch

Pull Requests

Add a Pull Request


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]
-Status: Open +Status: Closed -Package: Feature/Change Request +Package: *General Issues -Assigned To: +Assigned To: nikic
 [2016-01-15 17:56 UTC]
This has been implemented in PHP 7.0.
PHP Copyright © 2001-2023 The PHP Group
All rights reserved.
Last updated: Sat Apr 01 17:03:44 2023 UTC