|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2007-05-12 12:52 UTC] bugs dot php dot net at kreidenweis dot com
Description: ------------ substr() handled a negative $start parameter with an absolute value larger than the $string's length gracefully and sensibly up to PHP 5.2.1 In 5.2.2 this behavior changed without that being mentioned in the documentation. IMHO it probably has something to do with the fix for http://bugs.php.net/bug.php?id=40754 I guess (and hope ;) the behavior change wasn't intended. But if indeed so, please put a warning in the documentation. Reproduce code: --------------- var_dump(substr('abc', -4)); Expected result: ---------------- string(3) "abc" (up to PHP 5.2.1 this is what happens) Actual result: -------------- bool(false) (output by PHP 5.2.2) PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Mon Nov 17 20:00:01 2025 UTC |
I'm sorry, but this is a definite BC break and has bitten me both in Horde code and in my company's codebase. I've re-read the substr docs several times and I don't see any indication that a negative $start can cause substr to return false. Here's the description of the start parameter in its entirety: If start is non-negative, the returned string will start at the start'th position in string, counting from zero. For instance, in the string 'abcdef', the character at position 0 is 'a', the character at position 2 is 'c', and so forth. If start is negative, the returned string will start at the start'th character from the end of string. Example 2454. Using a negative start <?php $rest = substr("abcdef", -1); // returns "f" $rest = substr("abcdef", -2); // returns "ef" $rest = substr("abcdef", -3, 1); // returns "d" ... from http://us3.php.net/substr.Alright, here's the use case: I have a string. I want at most 16 characters of it. For all PHP versions before 5.2.[2 or 3], I could do this: $shorter = substr($string, -16); Now I have to do this: if (strlen($string) > 16)) $shorter = substr($string, -16); else $shorter = $string; My question is, especially since I'm asking that the historical behavior of PHP be maintained, how does this change improve the language? What is the point of it?