PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, September 5, 2022

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

 September 05, 2022     php, string, substr, trim     No comments   

Issue

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.


Solution

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.



Answered By - Matt K
Answer Checked By - Robin (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing