php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #52628 substr() returns false for empty string
Submitted: 2010-08-17 18:22 UTC Modified: 2010-08-17 22:28 UTC
Votes:65
Avg. Score:3.9 ± 1.2
Reproduced:45 of 50 (90.0%)
Same Version:38 (84.4%)
Same OS:35 (77.8%)
From: david at grudl dot com Assigned: kalle (profile)
Status: Closed Package: Strings related
PHP Version: Irrelevant OS:
Private report: No CVE-ID: None
 [2010-08-17 18:22 UTC] david at grudl dot com
Description:
------------
substr() should not return FALSE if is used with empty string. Yes, it is documented behaviour (If $string is less than or equal to $start characters long, FALSE will be returned), but it is not expected behaviour. There is no way to use "smaller $start".





Test script:
---------------
substr('x', 0, 2) // returns again 'x'

substr('', 0, 2) // returns FALSE but '' is expected


Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2010-08-17 22:19 UTC] kalle@php.net
-Status: Open +Status: Closed -Assigned To: +Assigned To: kalle
 [2010-08-17 22:19 UTC] kalle@php.net
I don't think it makes any sense to pass an empty string directly to substr and make it behave weirdly. Just wrap it inside an if statement to check if the string is empty if you are using userdata.

In either case, calling sub string on an empty string would return nothing, simply casting it to a string makes it empty:
$string = (string) substr('', 0, 2);
 [2010-08-17 22:22 UTC] david at grudl dot com
Example: I have string $s and want to short it to 5 characters:

$res = substr($s, 0, 5);

Question: is $res string of boolean?
 [2010-08-17 22:28 UTC] kalle@php.net
-Block user comment: N +Block user comment: Y
 [2010-08-17 22:28 UTC] kalle@php.net
Then check the return value of substr():

if(($string = substr($old_string, 0, 5)) === false) {
        /* error */
}

There is a million ways to over come this problem, simply check the string first before trying to substring it
 
PHP Copyright © 2001-2019 The PHP Group
All rights reserved.
Last updated: Tue Dec 10 11:01:23 2019 UTC