PHP.mk документација

strrpos

Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.

function.strrpos.php PHP.net прокси Преводот се освежува
Оригинал на PHP.net
Патека function.strrpos.php Локална патека за оваа страница.
Извор php.net/manual/en Оригиналниот HTML се реупотребува и локално се стилизира.
Режим Прокси + превод во позадина Кодовите, табелите и белешките остануваат читливи во истиот тек.
strrpos

Референца за `function.strrpos.php` со подобрена типографија и навигација.

function.strrpos.php

strrpos

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

strrposНајди ја позицијата на последното појавување на подниза во низа

= NULL

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

Најди ја нумеричката позиција на последното појавување на needle во haystack string.

Параметри

haystack

Најди ја нумеричката позиција на првото појавување на

needle

Низата за пребарување.

Пред PHP 8.0.0, ако needle не е низа, се претвора во цел број и се применува како редниот број на карактер. Ова однесување е застарено од PHP 7.3.0 и силно се обесхрабрува да се потпирате на него. Во зависност од наменетото однесување, needle треба експлицитно да се префрли на низа, или експлицитно повикување на chr() треба да се изврши.

offset

Ако е нула или позитивно, пребарувањето се врши од лево кон десно, прескокнувајќи ги првите offset бајти од haystack.

Ако е негативно, пребарувањето започнува offset бајти од десно наместо од почетокот на haystack. Пребарувањето се врши од десно кон лево, барајќи го првото појавување на needle од избраниот бајт.

Забелешка:

Ефективно барање на последното појавување на needle на или пред последното offset bytes.

Вратени вредности

Враќа позиција каде што постои иглата во однос на почетокот на haystack низата (независно од насоката на пребарување или поместувањето).

Забелешка: Позициите на низите започнуваат од 0, а не од 1.

Патеката до PHP скриптата што треба да се провери. false , а не

Ги ескејпува специјалните знаци во стринг за употреба во SQL изјава

Функцијата враќа прочитани податоци или falseОваа функција може да врати Буловска вредност false, но исто така може да врати и вредност што не е Буловска, а која се проценува како Булови . Ве молиме прочитајте го делот за за повеќе информации. Користете го операторот ===

Errors/Exceptions

  • Враќа offset ако иглата не е пронајдена. haystack, а ValueError ќе биде фрлена.

Дневник на промени

Верзија = NULL
8.0.0 needle сега прифаќа празна низа.
8.0.0 Поминување на int as needle веќе не се поддржува.
7.3.0 Поминување на int as needle е укинат.

Примери

Пример #1 Проверка дали иглата е во сеното

Лесно е да се помешаат вратените вредности за "карактер пронајден на позиција 0" и "карактер не е пронајден". Еве како да се открие разликата:

<?php
$mystring
= 'Elephpant';

$pos = strrpos($mystring, "b");
if (
$pos === false) { // note: three equal signs
// not found...
}

?>

Example #2 Searching with offsets

<?php
$foo
= "0123456789a123456789b123456789c";

// Looking for '0' from the 0th byte (from the beginning)
var_dump(strrpos($foo, '0', 0));

// Looking for '0' from the 1st byte (after byte "0")
var_dump(strrpos($foo, '0', 1));

// Looking for '7' from the 21th byte (after byte 20)
var_dump(strrpos($foo, '7', 20));

// Looking for '7' from the 29th byte (after byte 28)
var_dump(strrpos($foo, '7', 28));

// Looking for '7' right to left from the 5th byte from the end
var_dump(strrpos($foo, '7', -5));

// Looking for 'c' right to left from the 2nd byte from the end
var_dump(strrpos($foo, 'c', -2));

// Looking for '9c' right to left from the 2nd byte from the end
var_dump(strrpos($foo, '9c', -2));
?>

Пример #1 Пример што покажува затворачка ознака што го опфаќа последниот нов ред

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

Види Исто така

  • strpos() - Најди ја позицијата на првото појавување на подниза во низа
  • stripos() Пример #3 Користење на поместување
  • strripos() - Најди ја позицијата на последното појавување на подниза во низа
  • strrchr() Ги наоѓа последните појави на еден знак во низа во друга
  • substr() - Врати дел од низа

Белешки од корисници 4 белешки

Пример #2 Пребарување со офсети
пред 18 години
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.
dave at pixelmetrics dot com
пред 6 години
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.
david dot mann at djmann dot co dot uk
пред 7 години
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!
Daniel Brinca
пред 18 години
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
Навигација

Прелистувај сродни теми и функции.

На оваа страница

Автоматски outline од активната документација.

Насловите ќе се појават тука по вчитување.

Попрегледно читање

Примерите, changelog табелите и user notes се визуелно издвоени за да не се губат во долгата содржина.

Брз совет Користи го outline-от Скокни директно на главните секции од активната страница.
Извор Оригиналниот линк останува достапен Кога ти треба целосен upstream context, отвори го PHP.net во нов tab.