Simple way to implement this function in PHP 4<?phpif (function_exists('strripos') == false) { function strripos($haystack, $needle) { return strlen($haystack) - strpos(strrev($haystack), $needle); }}?>(PHP 5, PHP 7, PHP 8)
strripos — Encontra a posição da última ocorrência de uma substring em uma string, insensível a miúsculas/minúsculas
Encontra a posição numérica da última ocorrência de
needle na string haystack.
Diferentemente de strrpos(), strripos() é insensível a miúsculas/minúsculas.
haystackA string onde a substring será procurada.
needleA substring procurada.
Antes do PHP 8.0.0, se needle não for uma string, ela será convertida
para um número inteiro e aplicada como o valor ordinal de um caractere.
Este comportamento foi descontinuado a partir do PHP 7.3.0 e depender dele é altamente
desaconselhado. Dependendo do comportamento pretendido, o parâmetro
needle deve ser explicitamente convertido em string
ou uma chamada explícita para chr() deve ser realizada.
offset
Se zero ou positivo, a pesquisa é realizada da esquerda para a direita pulando os
primeiros offset bytes de
haystack.
Se negativo, a pesquisa é realizada da direita para a esquerda pulando os
últimos offset bytes de
haystack e pesquisando pela primeira ocorrência
de needle.
Nota:
Efetivamente, é o mesmo que procurar pela última ocorrência de
needleantes dos últimosoffsetbytes.
Retorna a posição onde a string procurada needle existe relativamente ao início da
string haystack (independente da direção de busca
ou de offset).
Nota: A posições na string iniciam em 0, e não em 1.
Retorna false se a string em needle não for encontrada.
Esta função pode
retornar o valor booleano false, mas também pode retornar um valor não booleano que pode ser
avaliado como false. Leia a seção sobre Booleanos para mais
informações. Use o operador
=== para testar o valor retornado por esta
função.
offset for maior que o comprimento de
haystack, um
ValueError será lançado.
| Versão | Descrição |
|---|---|
| 8.2.0 | A redução de todas as letras a maiúsculas ou minúsculas não depende mais da localidade definida com setlocale(). Somente a redução de todas as letras ASCII a maiúsculas ou minúsculas será feita. Os bytes não ASCII serão comparados por seu valor de byte. |
| 8.0.0 |
O parâmetro needle agora aceita uma string vazia.
|
| 8.0.0 |
Passar int no parâmetro needle não é mais suportado.
|
| 7.3.0 |
Passar um int no parâmetro needle foi descontinuado.
|
Exemplo #1 Um exemplo simples de strripos()
<?php
$haystack = 'ababcd';
$needle = 'aB';
$pos = strripos($haystack, $needle);
if ($pos === false) {
echo "Desculpe, não encontramos `$needle` em `$haystack`";
} else {
echo "Parabéns!\n";
echo "Encontramos a última ocorrência de `$needle` em `$haystack` na posição `$pos`";
}
?>O exemplo acima produzirá:
Parabéns! Encontramos a última ocorrência de `aB` em `ababcd` na posição `2`
Simple way to implement this function in PHP 4<?phpif (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:<?phpfunction 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:<?phpif(!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 )<?phpif(!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:<?phpif (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.