Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strrpos in PHP finding last character position instead?

Tags:

string

php

$string = "01234567890*****12345678901234567890*";  
echo strrpos($string,'*****');

why does this return 36 and not 15? (click here to test)

from php.net
strrpos — Find the position of the last occurrence of a substring in a string

What am I missing out on???
Thank you!

SOLUTION: using the answers bellow, I provided a PHP4 alternative

$haystack = "01234567890*****12345678901234567890*";  
$needle              = '*****';

$position = strlen($haystack) - strlen($needle) - strpos(strrev($haystack),strrev($needle));
echo $position; // 11
like image 703
Mohammad Avatar asked Aug 28 '11 12:08

Mohammad


People also ask

How can I get the last position of 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)

How do you find the last occurrence of a character?

strrchr() — Locate Last Occurrence of Character in String The strrchr() function finds the last occurrence of c (converted to a character) in string . The ending null character is considered part of the string . The strrchr() function returns a pointer to the last occurrence of c in string .


1 Answers

Probably you're using PHP 4:

from php.net

needle: If needle is not a string, it is converted to an integer and applied as the ordinal value of a character. The needle can only be a single character in PHP 4.

like image 197
Marek Sebera Avatar answered Nov 04 '22 11:11

Marek Sebera