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 — Возвращает позицию последнего вхождения подстроки без учёта регистра
Ищет позицию последнего вхождения подстроки needle
в строку haystack.
В отличие от strrpos(), strripos() не учитывает регистр символов.
haystackСтрока, в которой производится поиск.
needleСтрока для поиска.
До PHP 8.0.0 нестроковый аргумент needle
преобразовывался в целое число и заменялся на символ с этим порядковым значением в однобайтовой таблице символов.
Начиная с PHP 7.3.0 передача нестроковых значений устарела и полагаться на него настоятельно не рекомендуют.
Перед вызовом функции нестроковый аргумент needle требовалось
либо приводить к строке, либо получать строковое значение символа функцией chr().
offset
Если равно или больше ноля, то поиск будет идти слева направо
и, при этом, будут пропущены первые offset
байт строки haystack.
Если меньше ноля, то поиск будет идти справа налево. При этом
будут отброшены offset байт с конца
haystack и найдено первое найденное
вхождение needle.
Замечание:
Фактически это будет последнее вхождение
needleбез учётаoffsetпоследних байт.
Возвращает номер позиции последнего вхождения needle
относительно начала строки haystack (независимо от направления поиска и смещения (offset)).
Замечание: Позиция в строке строки отсчитывается от 0, а не от 1.
Возвращает false, если искомая строка не найдена.
Функция
возвращает как логическое значение false,
так и нелогическое значение, которое приводится к false.
Прочитайте раздел
«Логический тип»,
чтобы получить дополнительную информацию.
Используйте оператор ===
для проверки значения, которое возвращает функция.
| Версия | Описание |
|---|---|
| 8.2.0 | Приведение к единому регистру больше не зависит от региональных настроек, которые установили функцией setlocale(). Преобразовываются только символы кодировки ASCII. Байты, которые не относятся к кодировке ASCII, сравнятся по значению байта. |
| 8.0.0 |
Параметр needle теперь разрешает пустую строку.
|
| 8.0.0 |
Передача целого числа (int) в needle больше не поддерживается.
|
| 7.3.0 |
Передача целого числа (int) в needle объявлена устаревшей.
|
Пример #1 Пример использования strripos()
<?php
$haystack = 'ababcd';
$needle = 'aB';
$pos = strripos($haystack, $needle);
if ($pos === false) {
echo "К сожалению, ($needle) не найдена в ($haystack)";
} else {
echo "Поздравляем!\n";
echo "Последнее вхождение ($needle) найдено в ($haystack) в позиции ($pos)";
}
?>Результат выполнения приведённого примера:
Поздравляем! Последнее вхождение (aB) найдено в (ababcd) в позиции (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.