Edit report at http://bugs.php.net/bug.php?id=38437&edit=1

 ID:          38437
 Comment by:  salsi at icosaedro dot it
 Reported by: zizka at seznam dot cz
 Summary:     substr() - slightly change its contract
 Status:      Open
 Type:        Feature/Change Request
 Package:     Feature/Change Request
 PHP Version: 5.1.4

 New Comment:

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.


Previous Comments:
------------------------------------------------------------------------
[2006-08-12 20:34:14] 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.


------------------------------------------------------------------------



-- 
Edit this bug report at http://bugs.php.net/bug.php?id=38437&edit=1

Reply via email to