Skip to content
Advertisement

How does php substr deal with two offset values? [closed]

Consider the following:

echo substr("abcdefgh", 1, -1);
// outputs bcdefg  
echo substr("abcdefgh", 2, -2);
// outputs cdef

Seems like substr is taking first numeric parameter as offset from start of the string and the second parameter as another offset from the end of the string.

I went through the official docs https://www.php.net/manual/en/function.substr.php They don’t mention that there can be two offsets. They rather expect the second numeric parameter to be the length.

So, does substr take the second numeric argument as a second offset from the end when it is negative?


Edit: To further add to the question, as discussed in the comments, the docs mention:

If $length is given and is negative, then that many characters will be omitted from the end of string (after the start position has been calculated when a offset is negative).

This part is confusing, because It says after the start position has been calculated when a offset is negative. If we take the second numeric argument as length, then there is no offset which is negative.

Advertisement

Answer

You mustn’t have read far enough into the description!

If length is given and is negative, then that many characters will be omitted from the end of string…

https://www.php.net/manual/en/function.substr.php


Update based on edited question:

after the start position has been calculated when a offset is negative

This is simply clarifying that it will calculate the start position using the offset parameter first, then the length parameter second, rather than vice versa as that would give you differing results.

Consider this:

php > echo substr("phpisfun", -5, -2);
isf

If you were to modify this string using the length parameter first, followed by the offset, you would get the string “hpisf” instead.

It might seem like a confusing sentence at first but it’s bringing clarity to the execution order in this particular instance.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement