Search code examples
phpstrpos

strpos() not working with negative offset


I have a strange one, probably something silly, but I have been racking my brains for far too long on it.

I am using strpos() to see if a string ends with a certain substring, by using a negative offset of the length of said substring as per the PHP documentation. Which performs the search x chatacters from the end of the haystack, supposedly.

var_dump($recipient); //debug
if(strpos( $recipient, '_redacted', -9 ) === FALSE) {
   // do stuff
}

It just complains that the offset is not contained in the string. Yet the output is :

string(29) "fullname@company.tld_redacted"

A PHP Error was encountered

Severity: Warning Message: strpos(): Offset not contained in string

One can clearly see that the string is much longer than 9 characters, so why is it throwing that warning?(and by extension returning FALSE and always triggering my condition - incorrectly)


Solution

  • Support for negative offsets was added in PHP 7.1.
    You're likely running an older version.
    Always see the Changelog section on the manual page.