search for in the  
<strriposstrspn>
Last updated: Thu, 19 May 2005

strrpos

(PHP 3, PHP 4, PHP 5)

strrpos --  Find position of last occurrence of a char in a string

Description

int strrpos ( string haystack, string needle [, int offset] )

Returns the numeric position of the last occurrence of needle in the haystack string. Note that the needle in this case can only be a single character in PHP 4. If a string is passed as the needle, then only the first character of that string will be used.

If needle is not found, returns FALSE.

It is easy to mistake the return values for "character found at position 0" and "character not found". Here's how to detect the difference:

<?php

// in PHP 4.0b3 and newer:
$pos = strrpos($mystring, "b");
if (
$pos === false) { // note: three equal signs
   // not found...
}

// in versions older than 4.0b3:
$pos = strrpos($mystring, "b");
if (
is_bool($pos) && !$pos) {
  
// not found...
}
?>

If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.

Note: As of PHP 5.0.0 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.

Note: The needle may be a string of more than one character as of PHP 5.0.0.

See also strpos(), strripos(), strrchr(), substr(), stristr(), and strstr().



User Contributed Notes
strrpos
jonas at jonasbjork dot net
06-Apr-2005 03:25
I needed to remove last directory from an path, and came up with this solution:

<?php

  $path_dir
= "/my/sweet/home/";
 
$path_up = substr( $path_dir, 0, strrpos( $path_dir, '/', -2 ) )."/";
  echo
$path_up;

?>

Might be helpful for someone..
08-Mar-2005 01:14
In the below example, it should be substr, not strrpos.

<PHP?

$filename = substr($url, strrpos($url, '/') + 1);

?>
luca
20-Feb-2005 06:48
An easiser way for get a filename:
<PHP?

$filename = strrpos($url, strrpos($url, '/') + 1);

?>
escii at hotmail dot com ( Brendan )
10-Jan-2005 09:12
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;
}
?>
griffioen at justdesign dot nl
17-Nov-2004 12:57
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
07-Oct-2004 11:22
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<$pos_rule) { $last_pos = false; }
       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.
harlequin AT gmx DOT de
26-May-2004 11:59
this is my function for finding a filename in a URL:

<?php
  
function getfname($url){
      
$pos = strrpos($url, "/");
       if (
$pos === false) {
          
// not found / no filename in url...
          
return false;
       } else {
          
// Get the string length
          
$len = strlen($url);
           if (
$len < $pos){
                       print
"$len / $pos";
              
// the last slash we found belongs to http:// or it is the trailing slash of a URL
              
return false;
           } else {
              
$filename = substr($url, $pos+1, $len-$pos-1);
           }
       }
       return
$filename;
   }
?>
tsa at medicine dot wisc dot edu
24-May-2004 07:17
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:

<?php
function strrposmixed ($haystack, $needle, $start=0) {
  
// init start as the end of the str if not set
  
if($start == 0) {
      
$start = strlen($haystack);
   }
  
  
// 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) {
       return
false;
   } else {
       return
$lastFoundPos;
   }
}
?>
dreamclub2000 at hotmail dot com
04-Feb-2004 02:17
This function does what strrpos would if it handled multi-character strings:

<?php
function getLastStr($hay, $need){
 
$getLastStr = 0;
 
$pos = strpos($hay, $need);
  if (
is_int ($pos)){ //this is to decide whether it is "false" or "0"
  
while($pos) {
    
$getLastStr = $getLastStr + $pos + strlen($need);
    
$hay = substr ($hay , $pos + strlen($need));
    
$pos = strpos($hay, $need);
   }
   return
$getLastStr - strlen($need);
  } else {
   return -
1; //if $need wasnīt found it returns "-1" , because it could return "0" if itīs found on position "0".
 
}
}
?>
cagret at yahoo dot com
16-Dec-2003 11:12
This functions could be helpful:

<?php
/**
* @access public
* @package String
* @static
*/
class String {
  
  
/**
   * Replace only the first occurence of the search string with the replacement string
   * @param string $string
   * @param string $search
   * @param string $replace
   * @return string
   * @access public
   */
  
function replaceFirst($string, $search, $replace) {
      
$pos = strpos($string, $search);
       if (
is_int($pos)) {
          
$len = strlen($search);
           return
substr_replace($string, $replace, $pos, $len);
       }
       return
$string;
   }
  
  
/**
   * Replace only the last occurence of the search string with the replacement string
   * @param string $string
   * @param string $search
   * @param string $replace
   * @return string
   * @access public
   */
  
function replaceLast($string, $search, $replace) {
      
      
$pos = false;
      
       if (
is_int(strpos($string, $search))) {
          
$endPos = strlen($string);
           while (
$endPos > 0) {
              
$endPos = $endPos - 1;
              
$pos = strpos($string, $search, $endPos);
               if (
is_int($pos)) {
                   break;
               }
           }
       }
      
       if (
is_int($pos)) {
          
$len = strlen($search);
           return
substr_replace($string, $replace, $pos, $len);
       }
      
       return
$string;
   }
}
?>
dalroi
19-Nov-2003 07:11
The documentation doesn't tell, but strrpos returns an index counted from the left of the string, not from the right. That may save you testing for it, even though it's sort of obvious.
ZaraWebFX
14-Oct-2003 01:06
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");
?>
lee at 5ss dot net
29-Aug-2003 09:21
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!

<?php
//Find last occurance of needle in haystack
function str_rpos($haystack, $needle, $start = 0){
  
$tempPos = strpos($haystack, $needle, $start);
   if(
$tempPos === false){
       if(
$start == 0){
          
//Needle not in string at all
          
return false;
       }else{
          
//No more occurances found
          
return $start - strlen($needle);
       }
   }else{
      
//Find the next occurance
      
return str_rpos($haystack, $needle, $tempPos + strlen($needle));
   }
}
?>
ara at bluemedia dot us
14-Jul-2003 03:09
derek@slashview.com notes a great replacement for strrpos because of the single character needle limitation in the strrpos function. He made a slight error in the code. He adds the length of the needle string instead of subtracting it from the final position. The function should be:

<?php
function strlastpos($haystack, $needle) {
# flip both strings around and search, then adjust position based on string lengths
return strlen($haystack) - strlen($needle) - strpos(strrev($haystack), strrev($needle));
}
?>
no_spammage_at_wwwcrm_dot_com
24-Apr-2003 10:07
This function does what strrpos would if it handled multi-character strings:

<?php
//function recurses until it finds last instance of $needle in $haystack

function getLastStr($haystack, $needle, $first_time=1){

                
$test=strstr($haystack, $needle);//is the needle there?
                
if ($test) return getLastStr($test, $needle, 0);//see if there is another one?
                
else if ($first_time) return false;//there is no occurence at all
                
else return $haystack;//that was the last occurence

              
}
?>
FIE
15-Feb-2003 07:03
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:

<?php
function strlpos($f_haystack,$f_needle) {
    
$rev_str = strrev($f_needle);
    
$rev_hay = strrev($f_haystack);
    
$hay_len = strlen($f_haystack);
    
$ned_pos = strpos($rev_hay,$rev_str);
    
$result  = $hay_len - $ned_pos - strlen($rev_str);
     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!
rob at pulpchat dot com
22-Jan-2003 04:23
For those of you coming from VBScript, I have
converted the instrrev function to PHP:

<?php
function instrrev($n,$s) {
 
$x=strpos(chr(0).strrev($n),$s)+0;
  return ((
$x==0) ? 0 : strlen($n)-$x+1);
}
?>

Remember that, unlike PHP and Javascript, VBScript
returns 0 for no string found and 1 for the first
character position, etc.

Hopefully this will save some time if you are
converting ASP pages to PHP.
php dot net at insite-out dot com
17-Dec-2002 01:47
I was looking for the equivalent of Java's lastIndexOf(). I couldn't find it so I wrote this:

<?php
/*
Method to return the last occurrence of a substring within a
string
*/
function last_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.
su.noseelg@naes, only backwards
13-Dec-2002 12:39
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 '&nbsp;'.

<?php
function no_orphans($TheParagraph) {
   if (
substr_count($TheParagraph," ") > 1) {
  
$lastspace = strrpos($TheParagraph," ");
  
$TheParagraph = substr_replace($TheParagraph,"&nbsp;",$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&nbsp;dog." That way, the last two words will always stay together.
DONT SPAM vardges at iqnest dot com
30-Oct-2002 03:22
that function can be modified to this

<?php
function strrpos_str ($string, $searchFor, $startFrom = 0)
{
  
$addLen = strlen ($searchFor);
  
$endPos = $startFrom - $addLen;

   while (
true)
   {
       if ((
$newPos = strpos ($string, $searchFor, $endPos + $addLen)) === false) break;
      
$endPos = $newPos;
   }

   return (
$endPos >= 0) ? $endPos : false;
}

// example
$str = "abcabcabc";
$search = "ab";

$pos = strrpos_str ($str, $search);
if (
$pos === false) echo "not found";
else echo
$pos; // returns 6 in this case
?>
28-May-2002 02:46
Cause:
Find position of last occurrence of a string in a string...
and I needed it, I hacked a little code to do this:

Maybe it is helpful for you.

<?php
 
function _strrpos_needle($sourcestring,$needle){

  
/* just for easier understanding */
  
$tempString=$sourcestring;

   do {
    
$tempPos=strpos($tempString,$needle);
    
$tempString=substr($tempString,$tempPos+strlen($needle));
    
$realPos=$realPos+$tempPos;
   } while (!
is_bool($tempPos));

   return
$realPos;

  }
?>
derek at slashview dot com
01-Feb-2002 06:06
To find the position of the start of the last occurence of a string, we can do this:
$pos=strlen($haystack) - (strpos(strrev($haystack), strrev($needle)) + strlen($needle));
The idea is to reverse both $needle and $haystack, use strpos to find the first occurence of $needle in $haystack, then count backwards by the length of $needle. Finally, subtract $pos from length of $haystack. A lot easier to figure out if you use a test string to visualize it.  :)

<strriposstrspn>
 Last updated: Thu, 19 May 2005
Copyright © 2001-2005 The PHP Group
All rights reserved.
This unofficial mirror is operated at: The Server Pages
Last updated: Thu May 19 17:35:34 2005 CDT