strripos

(PHP 5)

strriposВозвращает позицию последнего вхождения подстроки без учета регистра

Описание

int strripos ( string $haystack , string $needle [, int $offset = 0 ] )

Ищет позицию последнего вхождения подстроки needle в строку haystack.

В отличие от strrpos(), strripos() не учитывает регистр символов.

Список параметров

haystack

Строка, в которой производится поиск.

needle

Если параметр needle не является строкой, то он будет преобразован к целому и обработан как код символа.

offset

Если указан, то поиск начнется с данного количества символов с начала строки. Если передано отрицательное значение, поиск начнется с указанного количества символов от конца строки, но по прежнему будет производится поиск последнего вхождения.

Возвращаемые значения

Возвращает номер позиции последнего вхождения needle относительно начала строки haystack (независимо от направления поиска и смещения (offset)). Также обратите внимание на то, что позиция строки отсчитывается от 0, а не от 1.

Возвращает FALSE, если искомая строка не найдена.

Внимание

Эта функция может возвращать как boolean FALSE, так и не-boolean значение, которое приводится к FALSE. За более подробной информацией обратитесь к разделу Булев тип. Используйте оператор === для проверки значения, возвращаемого этой функцией.

Примеры

Пример #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)

Смотрите также

  • strpos() - Возвращает позицию первого вхождения подстроки
  • stripos() - Возвращает позицию первого вхождения подстроки без учета регистра
  • strrpos() - Возвращает позицию последнего вхождения подстроки в строке
  • strrchr() - Находит последнее вхождение символа в строке
  • stristr() - Регистро-независимый вариант функции strstr
  • substr() - Возвращает подстроку

Коментарии

Автор:
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);
    }
}

?>
2007-07-03 13:47:30
http://php5.kiev.ua/manual/ru/function.strripos.html
Автор:
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.
2007-08-02 16:59:03
http://php5.kiev.ua/manual/ru/function.strripos.html
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 strrevsubstr$haystack0abs($offset) )  );
        }
        else{
           
$temp_cut strrevsubstr$haystack$offset )  );
        }
       
$pos strlen($haystack) - (strpos($temp_cutstrrev($needle)) + $offset strlen($needle));
        if (
$pos == strlen($haystack)) { $pos 0; }
        return 
$pos;
    }
/* endfunction strripos*/
}/* endfunction exists strripos*/
?>
2007-10-17 20:23:01
http://php5.kiev.ua/manual/ru/function.strripos.html
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 ){
        return 
strposstrtolower$str ), strtolower$needle ), $offset  );
    }
/* endfunction stripos */
}/* endfunction exists stripos */

if(!function_exists("strripos")){
    function 
strripos$haystack$needle$offset ) {
        if(  !
is_string$needle )  )$needle chrintval$needle )  );
        if( 
$offset ){
           
$temp_cut strrevsubstr$haystack0abs($offset) )  );
        }
        else{
           
$temp_cut strrev(    substr(   $haystack0max(  ( strlen($haystack) - $offset ), )   )    );
        }
        if(   ( 
$found stripos$temp_cutstrrev($needle) )  ) === FALSE   )return FALSE;
       
$pos = (   strlen$haystack  ) - (  $found $offset strlen$needle )  )   );
        return 
$pos;
    }
/* endfunction strripos */
}/* endfunction exists strripos */
?>
2008-04-20 17:14:26
http://php5.kiev.ua/manual/ru/function.strripos.html
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.
2008-09-25 12:31:19
http://php5.kiev.ua/manual/ru/function.strripos.html
strripos() has very strange behaviour when you provide search position. For some reason it searches forward from the given position, instead of searching backward, that is more logical. 

For example if you want to find instanse of $what, previous to the last, strripos($where, $what, $last_what_pos-1) will not wark as expected. It will return $last_what_pos again and again. And that has no sence at all.

To prevent this, I just used $prev_last_what_pos = strripos(substr($where,0,$last_what_pos), $what);
2010-03-08 21:00:53
http://php5.kiev.ua/manual/ru/function.strripos.html
Автор:
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.
2010-08-31 16:05:41
http://php5.kiev.ua/manual/ru/function.strripos.html

    Поддержать сайт на родительском проекте КГБ