brian at enchanter dot net
The documentation for 'offset' is misleading.
It says, "offset may be specified to begin searching an arbitrary number of characters into the string. Negative values will stop searching at an arbitrary point prior to the end of the string."
This is confusing if you think of strrpos as starting at the end of the string and working backwards.
A better way to think of offset is:
- If offset is positive, then strrpos only operates on the part of the string from offset to the end. This will usually have the same results as not specifying an offset, unless the only occurences of needle are before offset (in which case specifying the offset won't find the needle).
- If offset is negative, then strrpos only operates on that many characters at the end of the string. If the needle is farther away from the end of the string, it won't be found.
If, for example, you want to find the last space in a string before the 50th character, you'll need to do something like this:
strrpos($text, " ", -(strlen($text) - 50));
If instead you used strrpos($text, " ", 50), then you would find the last space between the 50th character and the end of the string, which may not have been what you were intending.
david dot mann at djmann dot co dot uk
Ten years on, Brian's note is still a good overview of how offsets work, but a shorter and simpler summary is:
strrpos($x, $y, 50); // 1: this tells strrpos() when to STOP, counting from the START of $x
strrpos($x, $y, -50); // 2: this tells strrpos() when to START, counting from the END of $x
Or to put it another way, a positive number lets you search the rightmost section of the string, while a negative number lets you search the leftmost section of the string.
Both these variations are useful, but picking the wrong one can cause some highly confusing results!
Daniel Brinca
Here is a simple function to find the position of the next occurrence of needle in haystack, but searching backwards (lastIndexOf type function):
//search backwards for needle in haystack, and return its position
function rstrpos ($haystack, $needle, $offset){
$size = strlen ($haystack);
$pos = strpos (strrev($haystack), $needle, $size - $offset);
if ($pos === false)
return false;
return $size - $pos;
}
Note: supports full strings as needle
fab
RE: hao2lian
There are a lot of alternative - and unfortunately buggy - implementations of strrpos() (or last_index_of as it was called) on this page. This one is a slight modifiaction of the one below, but it should world like a *real* strrpos(), because it returns false if there is no needle in the haystack.
if($index===false) {
returnfalse;
}$index=strlen($haystack) -strlen($needle) -$index;
return$index;
}?>
dave at pixelmetrics dot com
The description of offset is wrong. Here’s how it works, with supporting examples.
Offset effects both the starting point and stopping point of the search. The direction is always right to left. (The description wrongly says PHP searches left to right when offset is positive.)
Here’s how it works:
When offset is positive, PHP searches right to left from the end of haystack to offset. This ignores the left side of haystack.
When offset is negative, PHP searches right to left, starting offset bytes from the end, to the start of haystack. This ignores the right side of haystack.
Example 1:
$foo = ‘aaaaaaaaaa’;
var_dump(strrpos($foo, 'a', 5));
Result: int(10)
Example 2:
$foo = "aaaaaa67890";
var_dump(strrpos($foo, 'a', 5));
Result: int(5)
Conclusion: When offset is positive, PHP searches right to left from the end of haystack.
Example 3:
$foo = "aaaaa567890";
var_dump(strrpos($foo, 'a', 5));
Result: bool(false)
Conclusion: When offset is positive, PHP stops searching at offset.
Example 4:
$foo = ‘aaaaaaaaaa’;
var_dump(strrpos($foo, 'a', -5));
Result: int(6)
Conclusion: When offset is negative, PHP searches right to left, starting offset bytes from the end.
Example 5:
$foo = "a234567890";
var_dump(strrpos($foo, 'a', -5));
Result: int(0)
Conclusion: When offset is negative, PHP searches right to left, all the way to the start of haystack.
dmitry dot polushkin at gmail dot com
Returns the filename's string extension, else if no extension found returns false.
Example: filename_extension('some_file.mp3'); // mp3
Faster than the pathinfo() analogue in two times.
if($pos===false) {
returnfalse;
} else {
returnsubstr($filename,$pos+1);
}
}?>
escii at hotmail dot com ( Brendan )
I was immediatley pissed when i found the behaviour of strrpos ( shouldnt it be called charrpos ?) the way it is, so i made my own implement to search for strings.
function proper_strrpos($haystack,$needle){
while($ret = strrpos($haystack,$needle))
{
if(strncmp(substr($haystack,$ret,strlen($needle)),
$needle,strlen($needle)) == 0 )
return $ret;
$haystack = substr($haystack,0,$ret -1 );
}
return $ret;
}
?>
islandispeace at hotmail dot com
$offset is very misleading, here is my understanding:
function mystrrpos($haystack, $needle, $offset = 0) {
if ($offset == 0) {
return strrpos ($haystack, $needle);
} else {
return strrpos (substr($haystack, 0, $offset), $needle);
}
}
arlaud pierre
This seems to behave like the exact equivalent to the PHP 5 offset parameter for a PHP 4 version.
if($offset===0) returnstrrpos($haystack,$needle);$length=strlen($haystack);$size=strlen($needle);
if($offset<0) {$virtual_cut=$length+$offset;$haystack=substr($haystack,0,$virtual_cut+$size);$ret=strrpos($haystack,$needle);
return$ret>$virtual_cut?false:$ret;
} else {$haystack=substr($haystack,$offset);$ret=strrpos($haystack,$needle);
return$ret===false?$ret:$ret+$offset;
}
}?>
maxmike at gmail dot com
I've got a simple method of performing a reverse strpos which may be of use. This version I have treats the offset very simply:
Positive offsets search backwards from the supplied string index.
Negative offsets search backwards from the position of the character that many characters from the end of the string.
Here is an example of backwards stepping through instances of a string with this function:
<?phpfunctionbackwardStrpos ($haystack,$needle,$offset=0){$length=strlen($haystack);$offset= ($offset>0)?($length-$offset):abs($offset);$pos=strpos(strrev($haystack),strrev($needle),$offset);
return ($pos===false)?false:($length-$pos-strlen($needle) );
}$pos=0;$count=0;
echo"Test1
";
while(($pos=backwardStrpos("012340567890","0",$pos)) !==false){
echo$pos."
";$pos--;
if($pos<0){
echo"Done
";break;
}
}
echo"---===---
nTest2
";
echobackwardStrpos("12341234","1",2)."
";
echobackwardStrpos("12341234","1", -2);?>
Outputs:
Test1
11
5
0
Done
---===---
Test2
0
4
With Test2 the first line checks from the first 3 in "12341234" and runs backwards until it finds a 1 (at position 0)
The second line checks from the second 2 in "12341234" and seeks towards the beginning for the first 1 it finds (at position 4).
This function is useful for php4 and also useful if the offset parameter in the existing strrpos is equally confusing to you as it is for me.
FIE
refering to the comment and function about lastIndexOf()...
It seemed not to work for me the only reason I could find was the haystack was reversed and the string wasnt therefore it returnt the length of the haystack rather than the position of the last needle... i rewrote it as fallows:
return$result;
}?>
this one fallows the strpos syntax rather than java's lastIndexOf.
I'm not positive if it takes more resources assigning all of those variables in there but you can put it all in return if you want, i dont care if i crash my server ;).
~SILENT WIND OF DOOM WOOSH!
alexandre at NOSPAM dot pixeline dot be
I needed to check if a variable that contains a generated folder name based on user input had a trailing slash.
This did the trick:
gordon at kanazawa-gu dot ac dot jp
The "find-last-occurrence-of-a-string" functions suggested here do not allow for a starting offset, so here's one, tried and tested, that does:
function my_strrpos($haystack, $needle, $offset=0) {
// same as strrpos, except $needle can be a string
$strrpos = false;
if (is_string($haystack) && is_string($needle) && is_numeric($offset)) {
$strlen = strlen($haystack);
$strpos = strpos(strrev(substr($haystack, $offset)), strrev($needle));
if (is_numeric($strpos)) {
$strrpos = $strlen - $strpos - strlen($needle);
}
}
return $strrpos;
}
su.noseelg@naes, only backwards
Maybe I'm the only one who's bothered by it, but it really bugs me when the last line in a paragraph is a single word. Here's an example to explain what I don't like:
The quick brown fox jumps over the lazy
dog.
So that's why I wrote this function. In any paragraph that contains more than 1 space (i.e., more than two words), it will replace the last space with ' '.
if (substr_count($TheParagraph," ") >1) {$lastspace=strrpos($TheParagraph," ");$TheParagraph=substr_replace($TheParagraph," ",$lastspace,1);
}
return$TheParagraph;
}?>
So, it would change "The quick brown fox jumps over the lazy dog." to "The quick brown fox jumps over the lazy dog." That way, the last two words will always stay together.
stevewa
i wanted to find a leading space BEFORE a hyphen
Crude Oil (Dec) 51.00-56.00
so I had to find the position of the hyphen
then subtract that position from the length of the string (to make it a negative number)
and then walk left toward the beginning of the string, looking for the first space before the hyphen
ex:
$str_position_hyphen = strpos($line_new,"-",$str_position_spread);
$line_new_length = strlen($line_new);
$str_position_hyphen_from_end = $str_position_hyphen - $line_new_length;
echo "hyphen position from end = " . $str_position_hyphen_from_end . "
n";
$str_position_space_before_hyphen = strrpos($line_new, " ", $str_position_hyphen_from_end);
echo "*** previous space= " . $str_position_space_before_hyphen . "
n";
$line_new = substr_replace($line_new, ",", $str_position_space_before_hyphen, 1 );
echo $line_new . "
n";
lee at 5ss dot net
I should have looked here first, but instead I wrote my own version of strrpos that supports searching for entire strings, rather than individual characters. This is a recursive function. I have not tested to see if it is more or less efficient than the others on the page. I hope this helps someone!
if($tempPos===false){
if($start==0){//Needle not in string at allreturnfalse;
}else{//No more occurances foundreturn$start-strlen($needle);
}
}else{//Find the next occurancereturnstr_rpos($haystack,$needle,$tempPos+strlen($needle));
}
}?>
kavih7 at yahoo dot com
#
# DESCRIPTION:
# This function returns the last occurance of a string,
# rather than the last occurance of a single character like
# strrpos does. It also supports an offset from where to
# start the searching in the haystack string.
#
# ARGS:
# $haystack (required) -- the string to search upon
# $needle (required) -- the string you are looking for
# $offset (optional) -- the offset to start from
#
# RETURN VALS:
# returns integer on success
# returns false on failure to find the string at all
#
###################################################functionstrrpos_string($haystack,$needle,$offset=0)
{
if(trim($haystack) !=""&&trim($needle) !=""&&$offset<=strlen($haystack))
{$last_pos=$offset;$found=false;
while(($curr_pos=strpos($haystack,$needle,$last_pos)) !==false)
{$found=true;$last_pos=$curr_pos+1;
}
if($found)
{
return$last_pos-1;
}
else
{
returnfalse;
}
}
else
{
returnfalse;
}
}?>
genetically altered mastermind at gmail
Very handy to get a file extension:
$this->data['extension'] = substr($this->data['name'],strrpos($this->data['name'],'.')+1);
Christ Off
Function to truncate a string
Removing dot and comma
Adding ... only if a is character found
function TruncateString($phrase, $longueurMax = 150) {
$phrase = substr(trim($phrase), 0, $longueurMax);
$pos = strrpos($phrase, " ");
$phrase = substr($phrase, 0, $pos);
if ((substr($phrase,-1,1) == ",") or (substr($phrase,-1,1) == ".")) {
$phrase = substr($phrase,0,-1);
}
if ($pos === false) {
$phrase = $phrase;
}
else {
$phrase = $phrase . "...";
}
return $phrase;
}
griffioen at justdesign dot nl
If you wish to look for the last occurrence of a STRING in a string (instead of a single character) and don't have mb_strrpos working, try this:
function lastIndexOf($haystack, $needle) {
$index = strpos(strrev($haystack), strrev($needle));
$index = strlen($haystack) - strlen(index) - $index;
return $index;
}
nexman at playoutloud dot net
Function like the 5.0 version of strrpos for 4.x.
This will return the *last* occurence of a string within a string.
function strepos($haystack, $needle, $offset=0) {
$pos_rule = ($offset<0)?strlen($haystack)+($offset-1):$offset;
$last_pos = false; $first_run = true;
do {
$pos=strpos($haystack, $needle, (intval($last_pos)+(($first_run)?0:strlen($needle))));
if ($pos!==false && (($offset<0 && $pos <= $pos_rule) $offset >= 0)) {
$last_pos = $pos;
} else { break; }
$first_run = false;
} while ($pos !== false);
if ($offset>0 && $last_pos
return $last_pos;
}
If my math is off, please feel free to correct.
- A positive offset will be the minimum character index position of the first character allowed.
- A negative offset will be subtracted from the total length and the position directly before will be the maximum index of the first character being searched.
returns the character index ( 0+ ) of the last occurence of the needle.
* boolean FALSE will return no matches within the haystack, or outside boundries specified by the offset.
jafet at g dot m dot a dot i dot l dot com
Full strpos() functionality, by yours truly.
{# Why does strpos() do this? Anyway...if(!is_string($needle))$needle=ord(intval($needle));$haystack=strval($haystack);# Parameters$hlen=strlen($haystack);$nlen=strlen($needle);# Come on, this is a feature tooif($nlen==0)
{trigger_error(__FUNCTION__.'(): Empty delimiter.',E_USER_WARNING);
returnfalse;
}$offset=intval($offset);$hrev=strrev($haystack);$nrev=strrev($needle);# Search$pos=strpos($hrev,$nrev,$offset);
if($pos===false) returnfalse;
else return$hlen-$nlen-$pos;
}?>
Note that $offset is evaluated from the end of the string.
Also note that conforming_strrpos() performs some five times slower than strpos(). Just a thought.
php dot net at insite-out dot com
I was looking for the equivalent of Java's lastIndexOf(). I couldn't find it so I wrote this:
Method to return the last occurrence of a substring within a
string
*/functionlast_index_of($sub_str,$instr) {
if(strstr($instr,$sub_str)!="") {
return(strlen($instr)-strpos(strrev($instr),$sub_str));
}
return(-1);
}?>
It returns the numerical index of the substring you're searching for, or -1 if the substring doesn't exist within the string.
mijsoot_at_gmail_dot_com
To begin, i'm sorry for my English.
So, I needed of one function which gives me the front last position of a character.
Then I said myself that it should be better to make one which gives the "N" last position.
$return_context = "1173120681_0__0_0_Mijsoot_Thierry";
// Here i need to find = "Mijsoot_Thierry"
//echo $return_context."
";// -- DEBUG
function findPos($haystack,$needle,$position){
$pos = strrpos($haystack, $needle);
if($position>1){
$position --;
$haystack = substr($haystack, 0, $pos);
$pos = findPos($haystack,$needle,$position);
}else{
// echo $haystack."
"; // -- DEBUG
return $pos;
}
return $pos;
}
var_dump(findPos($return_context,"_",2)); // -- TEST
shimon at schoolportal dot co dot il
In strrstr function in php 4 there is also no offset.
// by Shimon Doodkin
function chrrpos($haystack, $needle, $offset=false)
{
$needle=$needle[0];
$l=strlen($haystack);
if($l==0) return false;
if($offset===false) $offset=$l-1;
else
{
if($offset>$l) $offset=$l-1;
if($offset<0) return false;
}
for(;$offset>0;$offset--)
if($haystack[$offset]==$needle)
return $offset;
return false;
}
?>
ZaraWebFX
this could be, what derek mentioned:
function cut_last_occurence($string,$cut_off) {
return strrev(substr(strstr(strrev($string), strrev($cut_off)),strlen($cut_off)));
}
// example: cut off the last occurence of "limit"
$str = "select delta_limit1, delta_limit2, delta_limit3 from table limit 1,7";
$search = " limit";
echo $str."n";
echo cut_last_occurence($str,"limit");
?>
tsa at medicine dot wisc dot edu
What the heck, I thought I'd throw another function in the mix. It's not pretty but the following function counts backwards from your starting point and tells you the last occurrance of a mixed char string:
}// searches backward from $start$currentStrPos=$start;$lastFoundPos=false;
while($currentStrPos!=0) {
if(!(strpos($haystack,$needle,$currentStrPos) ===false)) {$lastFoundPos=strpos($haystack,$needle,$currentStrPos);
break;
}$currentStrPos--;
}
if($lastFoundPos===false) {
returnfalse;
} else {
return$lastFoundPos;
}
}?>
jonas at jonasbjork dot net
I needed to remove last directory from an path, and came up with this solution:
$path_dir="/my/sweet/home/";$path_up=substr($path_dir,0,strrpos($path_dir,'/', -2) )."/";
echo$path_up;?>
Might be helpful for someone..
info at qrworld dot net
I made a function using strrpos to get the extension of a file.
function getExtension($file) {
$pos = strrpos($file, '.');
if($pos===false){
return false;
} else {
return substr($file, $pos+1);
}
}
The link of the post where I took the code is:
tremblay dot jf at gmail dot com
I created an easy function that search a substring inside a string.
It reverse the string and the substring inside an strpos and substract the result to the length of the string.
if (!function_exists("real_strrpos")) {
function real_strrpos($haystack,$needle) {
$pos = strlen($haystack);
$pos -= strpos(strrev($haystack), strrev($needle) );
$pos -= strlen($needle);
return $pos;
}
}
dixonmd at gmail dot com
$pos=strlen(string $haystack) -strpos(strrev(string $haystack),strrev(string $needle)) -strlen(string $needle);?>
If in the needle there is more than one character then in php 4 we can use the above statement for finding the position of last occurrence of a substring in a string instead of strrpos. Because in php 4 strrpos uses the first character of the substring.
eg :
$haystack="you you you you you";$needle="you";$pos1=strlen($haystack) -strpos(strrev($haystack),strrev($needle)) -strlen($needle);
echo$pos1."
";$pos2 strrpos($haystack,$needle);
echo$pos2."
";?>
php NO at SPAMMERS willfris SREMMAPS dot ON nl
** Maybe the shortest code to find the last occurence of a string, even in php4
*******/functionstringrpos($haystack,$needle,$offset=NULL)
{
returnstrlen($haystack)
-strpos(strrev($haystack) ,strrev($needle) ,$offset)
-strlen($needle);
}// @return -> chopped up for readability.?>
pb at tdcspace dot dk
what the hell are you all doing. Wanna find the *next* last from a specific position because strrpos is useless with the "offset" option, then....
ex: find 'Z' in $str from position $p, backward...
while($p > -1 and $str{$p} <> 'Z') $p--;
Anyone will notice $p = -1 means: *not found* and that you must ensure a valid start offset in $p, that is >=0 and < string length. Doh
purpleidea
I was having some issues when I moved my code to run it on a different server.
The earlier php version didn't support more than one character needles, so tada, bugs. It's in the docs, i'm just pointing it out in case you're scratching your head for a while.