字符串函数
在线手册:中文  英文

strrpos

(PHP 4, PHP 5)

strrpos计算指定字符串在目标字符串中最后一次出现的位置

说明

int strrpos ( string $haystack , string $needle [, int $offset = 0 ] )

返回字符串 haystackneedle 最后一次出现的数字位置。注意 PHP4 中,needle 只能为单个字符。如果 needle 被指定为一个字符串,那么将仅使用第一个字符。

参数

haystack

在此字符串中进行查找。

needle

如果 needle不是一个字符串,它将被转换为整型并被视为字符的顺序值。

offset

或许会查找字符串中任意长度的子字符串。负数值将导致查找在字符串结尾处开始的计数位置处结束。

返回值

返回 needle 存在的位置。如果没有找到,返回 FALSE。 Also note that string positions start at 0, and not 1.

Returns FALSE if the needle was not found.

Warning

此函数可能返回布尔值 FALSE,但也可能返回等同于 FALSE 的非布尔值。请阅读 布尔类型章节以获取更多信息。应使用 === 运算符来测试此函数的返回值。

更新日志

版本 说明
5.0.0 参数 needle 可以是一个多字符的字符串。
5.0.0 引入 offset 参数。

范例

Example #1 检查字串是否存在

很容易将“在位置 0 处找到”和“未发现字符串”这两种情况搞错。这是检测区别的办法:

<?php

$pos 
strrpos($mystring"b");
if (
$pos === false) { // 注意: 三个等号
    // 未发现...
}

?>

Example #2 使用偏移位置进行查找

<?php
$foo 
"0123456789a123456789b123456789c";

var_dump(strrpos($foo'7', -5));  // 从尾部第 5 个位置开始查找
                                   // 结果: int(17)

var_dump(strrpos($foo'7'20));  // 从第 20 个位置开始查找
                                   // 结果: int(27)

var_dump(strrpos($foo'7'28));  // 结果: bool(false)
?>

参见


字符串函数
在线手册:中文  英文

用户评论:

arlaud pierre (2012-07-02 13:51:28)

This seems to behave like the exact equivalent to the PHP 5 offset parameter for a PHP 4 version.

<?php
 
function strrpos_handmade($haystack$needle$offset 0){

  if(
$offset === 0) return strrpos($haystack$needle);
  
  
$length strlen($haystack);
  
$size strlen($needle);

  if(
$offset 0) {
    
$virtual_cut $length+$offset;
    
$haystack substr($haystack0$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 (2009-07-11 22:05:08)

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:

<?php
function backwardStrpos($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<br/>";
while((
$pos backwardStrpos("012340567890""0"$pos)) !== false){
     echo 
$pos."<br/>";
    
$pos--;
    if(
$pos 0){
        echo 
"Done<br/>";break;
    }
}
echo 
"---===---<br/>\nTest2<br/>";
echo 
backwardStrpos("12341234""1"2)."<br/>";
echo 
backwardStrpos("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.

alexandre at NOSPAM dot pixeline dot be (2008-12-20 08:35:00)

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:

<?php
    
// Detect and remove a trailing slash
    
$root_folder = ((strrpos($root_folder'/') + 1) == strlen($root_folder)) ? substr($root_folder0, - 1) : $root_folder;
?>

eagleeye at eeisi dot com (2008-07-02 17:44:19)

I had a problem where I was using the following in my .htaccess file.
php_value auto_prepend_file "pre.php"
php_value auto_append_file "post.php"
Not knowing how to prevent the htaccess directives from cascading, without having to put an override .htaccess in each subfolder, I figured, just prevent output in my pre and post scripts if we weren't in the root folder!
I did it using this line of code:
if (strrpos($_SERVER["REQUEST_URI"], "/") != 0) return;
Prevents execution of the rest of the script, and most importantly, doesn't output anything before any other headers may be sent by things in other folders (like my wiki site).

dixonmd at gmail dot com (2007-12-24 02:42:15)

<?php
        $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 : 
<?php
        $haystack 
"you you you you you";
        
$needle "you";
        
$pos1 strlen($haystack) - strpos (strrev($haystack), strrev($needle)) - strlen($needle);
        echo 
$pos1 "<br>";
        
$pos2 strrpos($haystack$needle);
        echo 
$pos2 "<br>";
?>

t dot hornberger at yatego dot com (2007-10-17 04:50:19)

the function posted is false, hier the correction:
function rstrpos ($haystack, $needle, $offset)
{
$size = strlen ($haystack);
$pos = strpos (strrev($haystack), strrev($needle), $size - $offset);

if ($pos === false)
return false;

return $size - $pos - strlen($needle);
}

Daniel Brinca (2007-10-15 05:41:05)

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

pb at tdcspace dot dk (2007-09-23 07:26:31)

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

brian at enchanter dot net (2007-07-16 07:47:14)

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.

jafet at g dot m dot a dot i dot l dot com (2007-04-12 19:08:56)

It would probably be good if someone would care to merge these little thoughts together...

<?php
function super_conforming_strrpos($haystack$needle$offset 0)
{
    
# Why does strpos() do this? Anyway...
    
if(!is_string($needle)) $needle ord(intval($needle));
    if(!
is_string($haystack)) $haystack strval($haystack);
    
# Setup
    
$offset intval($offset);
    
$hlen strlen($haystack);
    
$nlen strlen($needle);
    
# Intermezzo
    
if($nlen == 0)
    {
        
trigger_error(__FUNCTION__.'(): Empty delimiter.'E_USER_WARNING);
        return 
false;
    }
    if(
$offset 0)
    {
        
$haystack substr($haystack, -$offset);
        
$offset 0;
    }
    elseif(
$offset >= $hlen)
    {
        
trigger_error(__FUNCTION__.'(): Offset not contained in string.'E_USER_WARNING);
        return 
false;
    }
    
# More setup
    
$hrev strrev($haystack);
    
$nrev strrev($needle);
    
# Search
    
$pos strpos($hrev$nrev$offset);
    if(
$pos === false) return false;
    else return 
$hlen $nlen $pos;
}
?>

jafet at g dot m dot a dot i dot l dot com (2007-04-12 01:57:59)

Full strpos() functionality, by yours truly.

<?php
function conforming_strrpos($haystack$needle$offset 0)
{
    
# 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 too
    
if($nlen == 0)
    {
        
trigger_error(__FUNCTION__.'(): Empty delimiter.'E_USER_WARNING);
        return 
false;
    }
    
$offset intval($offset);
    
$hrev strrev($haystack);
    
$nrev strrev($needle);
    
# Search
    
$pos strpos($hrev$nrev$offset);
    if(
$pos === false) return false;
    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.

mijsoot_at_gmail_dot_com (2007-03-06 01:43:54)

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."<br />";// -- 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."<br />"; // -- DEBUG
return $pos;
}
return $pos;
}
var_dump(findPos($return_context,"_",2)); // -- TEST

Christ Off (2007-01-29 10:50:18)

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;
}

Guilherme Garnier (2007-01-15 02:44:37)

Actually, there is a little problem on your code: if $needle is not found inside $haystack, the function should return FALSE, but it is actually returning strlen($haystack) - strlen($needle). Here is a corrected version of it:

<?php
function stringrpos($haystack,$needle,$offset=NULL)
{
   if (
strpos($haystack,$needle,$offset) === FALSE)
      return 
FALSE;

   return 
strlen($haystack)
           - 
strposstrrev($haystack) , strrev($needle) , $offset)
           - 
strlen($needle);
}
?>

php NO at SPAMMERS willfris SREMMAPS dot ON nl (2006-12-20 18:48:56)

<?php
/*******
 ** Maybe the shortest code to find the last occurence of a string, even in php4
 *******/
function stringrpos($haystack,$needle,$offset=NULL)
{
    return 
strlen($haystack)
           - 
strposstrrev($haystack) , strrev($needle) , $offset)
           - 
strlen($needle);
}
// @return   ->   chopped up for readability.
?>

purpleidea (2006-11-27 00:07:46)

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.

dmitry dot polushkin at gmail dot com (2006-11-03 22:05:49)

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.
<?php
function filename_extension($filename) {
    
$pos strrpos($filename'.');
    if(
$pos===false) {
        return 
false;
    } else {
        return 
substr($filename$pos+1);
    }
}
?>

kavih7 at yahoo dot com (2006-06-08 12:53:10)

<?php
###################################################
#
# 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
#
###################################################

function strrpos_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
        {
            return 
false;
        }
    }
    else 
    {
        return 
false;
    }
}
?>

shimon at schoolportal dot co dot il (2006-05-03 11:31:08)

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;
}
?>

gordon at kanazawa-gu dot ac dot jp (2005-09-13 21:56:23)

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;
}

genetically altered mastermind at gmail (2005-08-22 10:30:57)

Very handy to get a file extension:
$this->data['extension'] = substr($this->data['name'],strrpos($this->data['name'],'.')+1);

fab (2005-08-10 04:07:05)

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.

<?php

function my_strrpos($haystack$needle) {
   
$index strpos(strrev($haystack), strrev($needle));
   if(
$index === false) {
        return 
false;
   }
   
$index strlen($haystack) - strlen($needle) - $index;
   return 
$index;
}

?>

lwoods (2005-08-06 12:03:25)

If you are a VBScript programmer ("ex-" of course), you will find that 'strrpos' doesn't work like the VBScript 'instrRev' function.
Here is the equivalent function:
VBScript:
k=instrrev(s,">",j);
PHP Equivalent of the above VBScript:
$k=strrpos(substr($s,0,$j),'>');
Comments:
You might think (I did!) that the following PHP function call would be the equivant of the above VBScript call:
$kk=strrpos($s,'>',$j);
NOPE! In the above PHP call, $j defines the position in the string that should be considered the BEGINNING of the string, whereas in the VBScript call, j is to be considered the END of the string, as far as this search is concerned. Anyway, the above 'strrpos' with the 'substr' will work.
(Probably faster to write a for loop!)

hao2lian (2005-08-02 19:50:29)

Yet another correction on the last_index_of function algorithm:
function last_index_of($haystack, $needle) {
$index = strpos(strrev($haystack), strrev($needle));
$index = strlen($haystack) - strlen($needle) - $index;
return $index;
}
"strlen(index)" in the most recent one should be "strlen($needle)".

jonas at jonasbjork dot net (2005-04-06 01:25:41)

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_dir0strrpos$path_dir'/', -) )."/";
  echo 
$path_up;

?>

Might be helpful for someone..

(2005-03-08 11:14:40)

In the below example, it should be substr, not strrpos.
<PHP?
$filename = substr($url, strrpos($url, '/') + 1);
?>

escii at hotmail dot com ( Brendan ) (2005-01-10 19:12:44)

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 (2004-11-17 10:57:26)

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 (2004-10-07 09:22:04)

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 (2004-05-26 09:59:31)

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 (2004-05-24 17:17:40)

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 (2004-02-04 12:17:21)

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".
  
}
}
?>

ZaraWebFX (2003-10-14 11:06:33)

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 (2003-08-29 07:21:10)

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 (2003-07-14 01:09:56)

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 (2003-04-24 08:07:27)

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$needle0);//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 (2003-02-15 05:03:24)

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 (2003-01-22 14:23:53)

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) ? 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 (2002-12-17 11:47:39)

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 (2002-12-13 10:39:21)

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 (2002-10-30 13:22:48)

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
?>

(2002-05-28 12:46:56)

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 (2002-02-01 16:06:41)

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. :)

易百教程