PHP 8.5.0 Alpha 1 available for testing

strrpos

(PHP 4, PHP 5, PHP 7, PHP 8)

strrposBusca la posición de la última ocurrencia de una subcadena en una cadena

Descripción

strrpos(string $haystack, string $needle, int $offset = 0): int|false

Busca la posición numérica de la última ocurrencia de needle en la cadena haystack.

Parámetros

haystack

La cadena en la que buscar.

needle

La cadena a buscar.

Si needle no es una cadena, se convierte a un entero y se aplica como el valor ordinal de un carácter. Este comportamiento está obsoleto a partir de PHP 7.3.0, por lo que su uso está totalmente desaconsejado. Dependiendo del comportamiento previsto, needle deberá ser convertido explícitamente a string, o realizar una llamada explícita a chr().

offset

Si es cero o positivo, la búsqueda se realiza de izquierda a derecha omitiendo los primeros offset bytes de haystack.

Si es negativo, la búsqueda comienza a offset bytes de la derecha en lugar de desde el inicio de haystack. La búsqueda se realiza de derecha a izquierda, buscando la primera ocurrencia de needle desde el byte seleccionado.

Nota:

Esto es efectivamente equivalente a buscar la última ocurrencia de needle en o antes de los últimos offset bytes.

Valores devueltos

Devuelve la posición de la última ocurrencia de needle en relación con el inicio de la cadena haystack (independientemente de la dirección de búsqueda o del offset).

Nota: Las posiciones de los chaîne de caractères comienzan en 0, y no en 1.

Devuelve false si needle no ha sido encontrado.

Advertencia

Esta función puede devolver el valor booleano false, pero también puede devolver un valor no booleano que se evalúa como false. Por favor lea la sección sobre Booleanos para más información. Use el operador === para comprobar el valor devuelto por esta función.

Historial de cambios

Versión Descripción
8.0.0 needle now accepts an empty string.
8.0.0 Pasar un entier como needle ya no está soportado.
7.3.0 Pasar un entier como before_needle ha sido declarado obsoleto.

Ejemplos

Ejemplo #1 Verifica si una ocurrencia es encontrada en una cadena

Es fácil cometer un error con respecto al valor devuelto entre "carácter encontrado en la posición 0" y "carácter no encontrado". A continuación se muestra cómo detectar esta diferencia:

<?php
$mystring
= 'Elephpant';

$pos = strrpos($mystring, "b");
if (
$pos === false) { // nota: 3 signos "="
// no encontrado...
}

?>

Ejemplo #2 Búsqueda con posiciones

<?php
$foo
= "0123456789a123456789b123456789c";

// Buscar '0' desde el byte 0 (desde el inicio)
var_dump(strrpos($foo, '0', 0));

// Buscar '0' desde el primer byte (después del byte "0")
var_dump(strrpos($foo, '0', 1));

// Buscar '7' desde el byte 21 (después del byte 20)
var_dump(strrpos($foo, '7', 20));

// Buscar '7' desde el byte 29 (después del byte 28)
var_dump(strrpos($foo, '7', 28));

// Buscar '7' de derecha a izquierda desde el quinto byte desde el final
var_dump(strrpos($foo, '7', -5));

// Buscar 'c' de derecha a izquierda desde el segundo byte desde el final
var_dump(strrpos($foo, 'c', -2));

// Buscar '9c' de derecha a izquierda desde el segundo byte desde el final
var_dump(strrpos($foo, '9c', -2));
?>

El resultado del ejemplo sería:

int(0)
bool(false)
int(27)
bool(false)
int(17)
bool(false)
int(29)

Ver también

  • strpos() - Busca la posición de la primera ocurrencia en un string
  • stripos() - Busca la posición de la primera ocurrencia en un string, sin distinguir mayúsculas de minúsculas
  • strripos() - Busca la posición de la última ocurrencia de un string contenido en otro, de forma insensible a mayúsculas y minúsculas
  • strrchr() - Encuentra la última ocurrencia de un carácter en un string
  • substr() - Devuelve un segmento de string

add a note

User Contributed Notes 4 notes

up
78
brian at enchanter dot net
17 years ago
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.
up
5
dave at pixelmetrics dot com
5 years ago
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.
up
3
david dot mann at djmann dot co dot uk
7 years ago
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!
up
6
Daniel Brinca
17 years ago
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
To Top