note 115627 added to function.substr

From: Date: Wed, 27 Aug 2014 22:14:29 +0000
Subject: note 115627 added to function.substr
Groups: php.notes 
Request: Send a blank email to php-notes+get-200328@lists.php.net to get a copy of this message
substr() exhibits rather unexpected behavior with respect to when it returns "" and when it returns FALSE. Specifically, the following appears to hold (tested on PHP 5.4.19): * if $string is "", it always returns FALSE * if ($start >= 0) and ($start >= strlen($string)) it returns FALSE * if ($start >= 0) and ($length<($start - strlen($string))) it returns FALSE * if ($start < 0) then it returns FALSE if *and only if* $length<-strlen($string). No other cases return FALSE. Note that in the last case, the position indicated by $start doesn't actually matter! Also worth noting is that if you supply a $start that is < -strlen($string), it will be treated exactly as if you had set $start = strlen($string). Here are some test cases to illustrate this behavior: substr("",0,0) === FALSE substr("",0,4) === FALSE substr("",-2,4) === FALSE substr("abc",3,0) === FALSE substr("abc",3,10) === FALSE substr("abc",3,-1) === FALSE substr("abc",0,-4) === FALSE substr("abc",2,-2) === FALSE substr("abc",-1,-4) === FALSE substr("abc",-4,-4) === FALSE substr("abc",-5,-4) === FALSE substr("abc",-10,-5) === FALSE substr("abc",-10,-2) === "a" substr("abc",-1,-3) === "" substr("abc",-1,-2) === "" substr("abc",-2,-3) === "" substr("abc",0,0) === "" substr("abc",-3,0) === "" substr("abc",-10,0) === "" substr("abc",-3,4) === "abc" substr("abc",-10,20) === "abc" substr("abc",-2,-2) === "" substr("abc",-2,1) === "b" substr("abc",0,-3) === "" substr("abc",2,-1) === "" ---- Server IP: 72.52.91.14 Probable Submitter: 124.168.127.231 ---- Manual Page -- http://php.net/manual/en/function.substr.php Edit -- https://master.php.net/note/edit/115627 Del: integrated -- https://master.php.net/note/delete/115627/integrated Del: useless -- https://master.php.net/note/delete/115627/useless Del: bad code -- https://master.php.net/note/delete/115627/bad+code Del: spam -- https://master.php.net/note/delete/115627/spam Del: non-english -- https://master.php.net/note/delete/115627/non-english Del: in docs -- https://master.php.net/note/delete/115627/in+docs Del: other reasons-- https://master.php.net/note/delete/115627 Reject -- https://master.php.net/note/reject/115627 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#200328) next »