|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[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.
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Wed Oct 29 01:00:01 2025 UTC |
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.