Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strpos does not search backwards on negative offset

Tags:

php

Update: I was looking at docs for strrpos thinking it was the docs for strpos. Sorry for the dumb mistake.

According to the docs, it says that when you provide a negative value as an offset argument, the function will start that many characters from the end of the string, searching backwards. It even shows this in Example #2. Why then can I not get this code to work properly?

$val = strpos('/imports/products/nin_avatar.png', '/', -2);

I am trying to get the index of the last forward slash in the string, yet it keeps returning false.. I've tried a couple different negative offsets, and none seem to work. Am I doing something wrong?

like image 851
Nick Rolando Avatar asked Jan 03 '13 23:01

Nick Rolando


People also ask

What does Strpos return if not found?

Return Value: Returns the position of the first occurrence of a string inside another string, or FALSE if the string is not found.

What is the strpos () function used for?

strpos in PHP is a built-in function. Its use is to find the first occurrence of a substring in a string or a string inside another string. The function returns an integer value which is the index of the first occurrence of the string.

Is Strpos case-sensitive PHP?

strpos() Function: This function helps us to find the position of the first occurrence of a string in another string. This returns an integer value of the position of the first occurrence of the string. This function is case-sensitive, which means that it treats upper-case and lower-case characters differently.

How can we find last occurrence of a character in a string in PHP?

The strrpos() function finds the position of the last occurrence of a string inside another string. Note: The strrpos() function is case-sensitive. Related functions: strpos() - Finds the position of the first occurrence of a string inside another string (case-sensitive)


2 Answers

It seems it works as the OP intended now in a new version of PHP.


Historical answer

The PHP manual for strpos() says...

Unlike strrpos() and strripos(), the offset cannot be negative.

Source.

This would be more obvious if you developed with warnings enabled. In your development instance, use something like error_reporting(E_ALL).

like image 181
alex Avatar answered Sep 28 '22 18:09

alex


Use strrpos instead of strpos.

like image 37
Bart Friederichs Avatar answered Sep 28 '22 19:09

Bart Friederichs