Web студия "GrandView"
  Главная   Написать Контакты
   
   
О проекте
Руководство php
 

strrpos

(PHP 3, PHP 4, PHP 5)

strrpos --  Возвращает позицию последнего вхождения символа

Описание

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

Возвращает позицию последнего вхождения needle в строку haystack. В PHP 4 используется только первый символ строки needle.

Если подстрока needle не найдена, возвращает FALSE.

Внимание

Эта функция может возвращать как логическое значение FALSE, так и не относящееся к логическому типу значение, которое приводится к FALSE, например, 0 или "". За более подробной информации обратитесь к разделу Булев тип. Используйте оператор === для проверки значения, возвращаемого этой функцией.

Если needle не является строкой, он приводится к целому и трактуется как код символа.

Замечание: Начиная с PHP 5.0.0, необязательный аргумент offset позволяет указать, с какого по счету символа строки haystack начинать поиск. Отрицательное значение предписывает прекратить поиск при достижении определенной позиции до конца строки.

Замечание: Начиная с PHP 5.0.0 needle используется полностью (а не только первый символ).

См. также описание функций strpos(), strripos(), strrchr(), substr(), stristr() и strstr().



strspn> <strripos
Last updated: Fri, 26 Jan 2007
 
add a note add a note User Contributed Notes
strrpos
t dot hornberger at yatego dot com
17-Oct-2007 04:50
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
15-Oct-2007 05:41
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
23-Sep-2007 07:26
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
16-Jul-2007 07:47
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
12-Apr-2007 07:08
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
12-Apr-2007 01:57
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
06-Mar-2007 01:43
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
29-Jan-2007 10:50
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
15-Jan-2007 02:44
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)
           -
strpos( strrev($haystack) , strrev($needle) , $offset)
           -
strlen($needle);
}
?>
php NO at SPAMMERS willfris SREMMAPS dot ON nl
20-Dec-2006 06:48
<?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)
           -
strpos( strrev($haystack) , strrev($needle) , $offset)
           -
strlen($needle);
}
// @return   ->   chopped up for readability.
?>
purpleidea
27-Nov-2006 12:07
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
06-Nov-2006 04:04
Back to previous post... if you are using the PHP >=5.2 then use the simply:
<?php pathinfo($filename, PATHINFO_EXTENSION); ?>
dmitry dot polushkin at gmail dot com
03-Nov-2006 10:05
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
08-Jun-2006 12:53
###################################################
#
# 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
03-May-2006 11:31
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;
}
?>
clan_ghw2 at hotmail dot com
02-Feb-2006 11:28
Brian below is incorrect about strrpos on different platforms.

Tested on Home PC (win32 + PHP 5.1.2) and Web Server (linux + 4.4.1)

echo strrpos("blah.blahannila","blaha");
returns 5 on windows
returns 5 on linux

Could've been a bug with an earlier PHP version, however the latest version of PHP returns position of the beginning of the string we're trying to find.

-Thaddeus
nh_handyman
22-Sep-2005 03:59
As noted in some examples below, strrpos does not act the same on every platform!

On Linux, it returns the position of the end of the target
On Windows, it returns the position of the start of the target

strrpos ("c:/somecity/html/t.php")

returns 11 on Windows
returns 16 on Linux

Brian
gordon at kanazawa-gu dot ac dot jp
13-Sep-2005 09:56
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
22-Aug-2005 10:30
Very handy to get a file extension:
$this->data['extension'] = substr($this->data['name'],strrpos($this->data['name'],'.')+1);
fab
10-Aug-2005 04:07
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
06-Aug-2005 12:03
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
02-Aug-2005 07:50
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
06-Apr-2005 01: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 11:14
In the below example, it should be substr, not strrpos.

<PHP?

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

?>
escii at hotmail dot com ( Brendan )
10-Jan-2005 07: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 10: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 09: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 09: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 05: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 12: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
Новости
11 июля 2007
Сайт запущен
© 2007 info@grandviewstudio.com

Deprecated: Function set_magic_quotes_runtime() is deprecated in /home/sites/grandviewstudiocom/www/65f67d67a94ad980786580ae69e11c07/sape.php on line 324

Deprecated: Function set_magic_quotes_runtime() is deprecated in /home/sites/grandviewstudiocom/www/65f67d67a94ad980786580ae69e11c07/sape.php on line 330
Z058440144362 Z348613067571