strrpos
(PHP 4, PHP 5)
strrpos — Find the position of the last occurrence of a substring in a string
Description
$haystack
, string $needle
[, int $offset
= 0
] )
Find the numeric position of the last occurrence of
needle
in the haystack
string.
Parameters
-
haystack
-
The string to search in.
-
needle
-
If
needle
is not a string, it is converted to an integer and applied as the ordinal value of a character. -
offset
-
If specified, search will start this number of characters counted from the beginning of the string. If the value is negative, search will instead start from that many characters from the end of the string, searching backwards.
Return Values
Returns the position where the needle exists relative to the beginnning of
the haystack
string (independent of search direction
or offset).
Also note that string positions start at 0, and not 1.
Returns FALSE
if the needle was not found.
This function may
return Boolean FALSE
, but may also return a non-Boolean value which
evaluates to FALSE
. Please read the section on Booleans for more
information. Use the ===
operator for testing the return value of this
function.
Changelog
Version | Description |
---|---|
5.0.0 |
The needle may now be a string of more than one
character.
|
5.0.0 |
The offset parameter was introduced.
|
Examples
Example #1 Checking if a needle is in the haystack
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
$pos = strrpos($mystring, "b");
if ($pos === false) { // note: three equal signs
// not found...
}
?>
Example #2 Searching with offsets
<?php
$foo = "0123456789a123456789b123456789c";
var_dump(strrpos($foo, '7', -5)); // Starts looking backwards five positions
// from the end. Result: int(17)
var_dump(strrpos($foo, '7', 20)); // Starts searching 20 positions into the
// string. Result: int(27)
var_dump(strrpos($foo, '7', 28)); // Result: bool(false)
?>
See Also
- strpos() - Find the position of the first occurrence of a substring in a string
- stripos() - Find the position of the first occurrence of a case-insensitive substring in a string
- strripos() - Find the position of the last occurrence of a case-insensitive substring in a string
- strrchr() - Find the last occurrence of a character in a string
- substr() - Return part of a string
- addcslashes
- addslashes
- bin2hex
- chop
- chr
- chunk_split
- convert_cyr_string
- convert_uudecode
- convert_uuencode
- count_chars
- crc32
- crypt
- echo
- explode
- fprintf
- get_html_translation_table
- hebrev
- hebrevc
- hex2bin
- html_entity_decode
- htmlentities
- htmlspecialchars_decode
- htmlspecialchars
- implode
- join
- lcfirst
- levenshtein
- localeconv
- ltrim
- md5_file
- md5
- metaphone
- money_format
- nl_langinfo
- nl2br
- number_format
- ord
- parse_str
- printf
- quoted_printable_decode
- quoted_printable_encode
- quotemeta
- rtrim
- setlocale
- sha1_file
- sha1
- similar_text
- soundex
- sprintf
- sscanf
- str_getcsv
- str_ireplace
- str_pad
- str_repeat
- str_replace
- str_rot13
- str_shuffle
- str_split
- str_word_count
- strcasecmp
- strchr
- strcmp
- strcoll
- strcspn
- strip_tags
- stripcslashes
- stripos
- stripslashes
- stristr
- strlen
- strnatcasecmp
- strnatcmp
- strncasecmp
- strncmp
- strpbrk
- strpos
- strrchr
- strrev
- strripos
- strrpos
- strspn
- strstr
- strtok
- strtolower
- strtoupper
- strtr
- substr_compare
- substr_count
- substr_replace
- substr
- trim
- ucfirst
- ucwords
- vfprintf
- vprintf
- vsprintf
- wordwrap
Коментарии
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");
?>
Very handy to get a file extension:
$this->data['extension'] = substr($this->data['name'],strrpos($this->data['name'],'.')+1);
<?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.
?>
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.
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
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!
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.