Simple way to implement this function in PHP 4
<?php
if (function_exists('strripos') == false) {
function strripos($haystack, $needle) {
return strlen($haystack) - strpos(strrev($haystack), $needle);
}
}
?>
(PHP 5, PHP 7, PHP 8)
strripos — Busca la posición de la última ocurrencia de un string contenido en otro, de forma insensible a mayúsculas y minúsculas
Busca la posición numérica de la última ocurrencia de
needle
en el string
haystack
.
A diferencia de la función strrpos(), strripos() es insensible a mayúsculas y minúsculas.
haystack
El string en el que se debe buscar.
needle
El string 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 se realiza de derecha a izquierda
omitiendo los últimos offset
bytes de
haystack
y buscando la primera ocurrencia
de needle
.
Nota:
Esto es efectivamente buscar la última ocurrencia de
needle
antes de los últimosoffset
bytes.
Devuelve la posición de la última ocurrencia de needle
en relación con el inicio del string 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.
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.
Versión | Descripción |
---|---|
8.2.0 | Case folding no longer depends on the locale set with setlocale(). Only ASCII case folding will be done. Non-ASCII bytes will be compared by their byte value. |
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.
|
Ejemplo #1 Ejemplo con strripos()
<?php
$haystack = 'ababcd';
$needle = 'aB';
$pos = strripos($haystack, $needle);
if ($pos === false) {
echo "Lo sentimos, no se pudo encontrar ($needle) en ($haystack)";
} else {
echo "¡Felicidades!\n";
echo "Hemos encontrado el último ($needle) en ($haystack) en la posición ($pos)";
}
?>
El resultado del ejemplo sería:
¡Felicidades! Hemos encontrado el último (aB) en (ababcd) en la posición (2)
Simple way to implement this function in PHP 4
<?php
if (function_exists('strripos') == false) {
function strripos($haystack, $needle) {
return strlen($haystack) - strpos(strrev($haystack), $needle);
}
}
?>
Suppose you just need a stripos function working backwards expecting that strripos does this job, you better use the following code of a custom function named strbipos:
<?php
function strbipos($haystack="", $needle="", $offset=0) {
// Search backwards in $haystack for $needle starting from $offset and return the position found or false
$len = strlen($haystack);
$pos = stripos(strrev($haystack), strrev($needle), $len - $offset - 1);
return ( ($pos === false) ? false : $len - strlen($needle) - $pos );
}
// Test
$body = "01234Xy7890XYz456xy90";
$str = "xY";
$len = strlen($body);
echo "TEST POSITIVE offset VALUES IN strbipos<br>";
for ($i = 0; $i < $len; $i++) {
echo "Search in [$body] for [$str] starting from offset [$i]: [" . strbipos($body, $str, $i) . "]<br>";
}
?>
Note that this function does exactly what it says and its results are different comparing to PHP 5 strripos function.
I think you shouldn't underestimate the length of $needle in the search of THE FIRST POSITION of it's last occurrence in the string. I improved the posted function, with added support for offset. I think this is an exact copy of the real function:
<?php
if(!function_exists("strripos")){
function strripos($haystack, $needle, $offset=0) {
if($offset<0){
$temp_cut = strrev( substr( $haystack, 0, abs($offset) ) );
}
else{
$temp_cut = strrev( substr( $haystack, $offset ) );
}
$pos = strlen($haystack) - (strpos($temp_cut, strrev($needle)) + $offset + strlen($needle));
if ($pos == strlen($haystack)) { $pos = 0; }
return $pos;
}/* endfunction strripos*/
}/* endfunction exists strripos*/
?>
OK, I guess this will be the final function implementation for PHP 4.x versions ( my previous posts are invalid )
<?php
if(!function_exists("stripos")){
function stripos( $str, $needle, $offset = 0 ){
return strpos( strtolower( $str ), strtolower( $needle ), $offset );
}/* endfunction stripos */
}/* endfunction exists stripos */
if(!function_exists("strripos")){
function strripos( $haystack, $needle, $offset = 0 ) {
if( !is_string( $needle ) )$needle = chr( intval( $needle ) );
if( $offset < 0 ){
$temp_cut = strrev( substr( $haystack, 0, abs($offset) ) );
}
else{
$temp_cut = strrev( substr( $haystack, 0, max( ( strlen($haystack) - $offset ), 0 ) ) );
}
if( ( $found = stripos( $temp_cut, strrev($needle) ) ) === FALSE )return FALSE;
$pos = ( strlen( $haystack ) - ( $found + $offset + strlen( $needle ) ) );
return $pos;
}/* endfunction strripos */
}/* endfunction exists strripos */
?>
Generally speaking, linear searches are from start to end, not end to start - which makes sense from a human perspective. If you need to find strings in a string backwards, reverse your haystack and needle rather than manually chopping it up.
Sorry, I made that last post a bit prematurely. One more thing wrong with the simple php4 version is that it breaks if the string is not found. It should actually look like this:
<?php
if (function_exists('strripos') == false) {
function strripos($haystack, $needle) {
$pos = strlen($haystack) - strpos(strrev($haystack), strrev($needle));
if ($pos == strlen($haystack)) { $pos = 0; }
return $pos;
}
}
?>
Note, we now check to see if the $needle was found, and if it isn't, we return 0.