Louis M.
Louis M.

Reputation: 143

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) "[email protected]_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)

Upvotes: 1

Views: 1065

Answers (4)

user2587656
user2587656

Reputation: 419

I had that error too. With that error it produced also a stack trace:

Fatal error: Uncaught ValueError: strrpos(): Argument #3 ($offset) must be contained in argument #1 ($haystack) in proc.php:963
Stack trace:
#0 proc.php(963): strpos('', '`', -1)
#1 {main}
thrown in proc.php on line 963

As you see it tells that the first argument (a variable in the code) had evaluated to an empty string and the negative offset 1 in that empty string was not allowed. So it looks like you will always have to use a strlen check if this kind of situation can happen.

BTW: strrpos is not a solution. If you replace the above code with "strrpos('', '`', 1)" you get the same error.

Upvotes: 0

sabrine abdelkebir
sabrine abdelkebir

Reputation: 83

Use strrpos instead of strpos.

Upvotes: 1

Adrian Bean
Adrian Bean

Reputation: 33

you could try changing the logic of your if statement thus

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

Try that and let me know if it works for you

Upvotes: -2

deceze
deceze

Reputation: 522626

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.

Upvotes: 4

Related Questions