php последнее вхождение подстроки в строку

strpos

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

strpos — Возвращает позицию первого вхождения подстроки

Описание

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

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

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

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

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

Список изменений

Примеры

Пример #1 Использование ===

Пример #3 Использование смещения

Примечания

Замечание: Эта функция безопасна для обработки данных в двоичной форме.

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

User Contributed Notes 38 notes

As strpos may return either FALSE (substring absent) or 0 (substring at start of string), strict versus loose equivalency operators must be used very carefully.

To know that a substring is absent, you must use:

To know that a substring is present (in any position including 0), you can use either of:

To know that a substring is at the start of the string, you must use:

To know that a substring is in any position other than the start, you can use any of:

This is a function I wrote to find all occurrences of a string, using strpos recursively.

It is interesting to be aware of the behavior when the treatment of strings with characters using different encodings.

# Now, encoding the string «Fábio» to utf8, we get some «unexpected» outputs. Every letter that is no in regular ASCII table, will use 4 positions(bytes). The starting point remains like before.
# We cant find the characted, because the haystack string is now encoded.
var_dump ( strpos ( utf8_encode ( «Fábio» ), ‘á’ ));
#bool(false)

# To get the expected result, we need to encode the needle too
var_dump ( strpos ( utf8_encode ( «Fábio» ), utf8_encode ( ‘á’ )));
#int(1)

# And, like said before, «á» occupies 4 positions(bytes)
var_dump ( strpos ( utf8_encode ( «Fábio» ), ‘b’ ));
#int(5)

I lost an hour before I noticed that strpos only returns FALSE as a boolean, never TRUE.. This means that

is a different beast then:

since the latter will never be true. After I found out, The warning in the documentation made a lot more sense.

Warning:
this is not unicode safe

strpos($word,’?’) in e?ez-> 1
strpos($word,’?’) in è?ent-> 2

when you want to know how much of substring occurrences, you’ll use «substr_count».
But, retrieve their positions, will be harder.
So, you can do it by starting with the last occurrence :

Docs are missing that WARNING is issued if needle is » (empty string).

In case of empty haystack it just return false:

Warning: strpos(): Empty needle in /in/lADCh on line 3
bool(false)

Warning: strpos(): Empty needle in /in/lADCh on line 7
bool(false)

Note also that warning text may differ depending on php version, see https://3v4l.org/lADCh

Parse strings between two others in to array.

Can be helpfull to custom parsing 🙂

My version of strpos with needles as an array. Also allows for a string, or an array inside an array.

add quotes to the needle

If you would like to find all occurences of a needle inside a haystack you could use this function strposall($haystack,$needle);. It will return an array with all the strpos’s.

The most straightforward way to prevent this function from returning 0 is:

Note this code example below in PHP 7.3
= «17,25» ;

This just gave me some headache since the value I am checking against comes from the database as an integer.

When a value can be of «unknow» type, I find this conversion trick usefull and more readable than a formal casting (for php7.3+):

Find position of nth occurrence of a string:

This function raises a warning if the offset is not between 0 and the length of string:

Warning: strpos(): Offset not contained in string in %s on line %d

To prevent others from staring at the text, note that the wording of the ‘Return Values’ section is ambiguous.

strpos($myString, ‘b’, 40) returns 43, great.

And now the text: «Returns the position of where the needle exists relative to the beginning of the haystack string (independent of offset).»

So it doesn’t really matter what offset I specify; I’ll get the REAL position of the first occurrence in return, which is 3?

«independent of offset» means, you will get the REAL positions, thus, not relative to your starting point (offset).

Substract your offset from strpos()’s answer, then you have the position relative to YOUR offset.

A function I made to find the first occurrence of a particular needle not enclosed in quotes(single or double). Works for simple nesting (no backslashed nesting allowed).

This might be useful.

if you want to get the position of a substring relative to a substring of your string, BUT in REVERSE way:

Источник

strripos

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

Описание

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

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

Фактически это будет последнее вхождение needle без учёта offset последних байт.

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

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

Замечание: Позиция в строке строки отсчитывается от 0, а не от 1.

Список изменений

ВерсияОписание
8.0.0Передача целого числа ( int ) в needle больше не поддерживается.
7.3.0Передача целого числа ( int ) в needle объявлена устаревшей.

Примеры

Пример #1 Пример использования strripos()

= ‘ababcd’ ;
$needle = ‘aB’ ;

Результат выполнения данного примера:

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

User Contributed Notes 7 notes

Simple way to implement this function in PHP 4

OK, I guess this will be the final function implementation for PHP 4.x versions ( my previous posts are invalid )

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:

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:

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.

Источник

strrpos

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

strrpos — Возвращает позицию последнего вхождения подстроки в строке

Описание

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

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

Фактически это будет последнее вхождение needle без учёта offset последних байт.

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

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

Замечание: Позиция в строке строки отсчитывается от 0, а не от 1.

Список изменений

ВерсияОписание
8.0.0Передача целого числа ( int ) в needle больше не поддерживается.
7.3.0Передача целого числа ( int ) в needle объявлена устаревшей.

Примеры

Пример #1 Проверка существования искомой строки

Легко ошибиться и перепутать возвращаемые значения в случаях «символ найден в нулевой позиции» и «символ не найден». Вот так можно узнать разницу:

Пример #2 Поиск со смещением

Результат выполнения данного примера:

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

User Contributed Notes 35 notes

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:

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.

Ten years on, Brian’s note is still a good overview of how offsets work, but a shorter and simpler summary is:

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!

Here is a simple function to find the position of the next occurrence of needle in haystack, but searching backwards (lastIndexOf type function):

if ($pos === false)
return false;

Note: supports full strings as needle

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.

Conclusion: When offset is negative, PHP searches right to left, starting offset bytes from the end.

Conclusion: When offset is negative, PHP searches right to left, all the way to the start of haystack.

To understand this instinctively, just imagine the characters being replaced with invalid symbols. Here’s an example:

$offset is very misleading, here is my understanding:

This seems to behave like the exact equivalent to the PHP 5 offset parameter for a PHP 4 version.

Maybe I’m the only one who’s bothered by it, but it really bugs me when the last line in a paragraph is a single word. Here’s an example to explain what I don’t like:

The quick brown fox jumps over the lazy
dog.

So that’s why I wrote this function. In any paragraph that contains more than 1 space (i.e., more than two words), it will replace the last space with ‘ ‘.

I’ve got a simple method of performing a reverse strpos which may be of use. This version I have treats the offset very simply:
Positive offsets search backwards from the supplied string index.
Negative offsets search backwards from the position of the character that many characters from the end of the string.

Here is an example of backwards stepping through instances of a string with this function:

With Test2 the first line checks from the first 3 in «12341234» and runs backwards until it finds a 1 (at position 0)

The second line checks from the second 2 in «12341234» and seeks towards the beginning for the first 1 it finds (at position 4).

This function is useful for php4 and also useful if the offset parameter in the existing strrpos is equally confusing to you as it is for me.

I needed to check if a variable that contains a generated folder name based on user input had a trailing slash.

This did the trick:

The «find-last-occurrence-of-a-string» functions suggested here do not allow for a starting offset, so here’s one, tried and tested, that does:

refering to the comment and function about lastIndexOf().
It seemed not to work for me the only reason I could find was the haystack was reversed and the string wasnt therefore it returnt the length of the haystack rather than the position of the last needle. i rewrote it as fallows:

SILENT WIND OF DOOM WOOSH!

Full strpos() functionality, by yours truly.

Also note that conforming_strrpos() performs some five times slower than strpos(). Just a thought.

i wanted to find a leading space BEFORE a hyphen

Crude Oil (Dec) 51.00-56.00

so I had to find the position of the hyphen

then subtract that position from the length of the string (to make it a negative number)
and then walk left toward the beginning of the string, looking for the first space before the hyphen

I should have looked here first, but instead I wrote my own version of strrpos that supports searching for entire strings, rather than individual characters. This is a recursive function. I have not tested to see if it is more or less efficient than the others on the page. I hope this helps someone!

I needed to remove last directory from an path, and came up with this solution:

?>

Might be helpful for someone..

If you wish to look for the last occurrence of a STRING in a string (instead of a single character) and don’t have mb_strrpos working, try this:

Function like the 5.0 version of strrpos for 4.x.
This will return the *last* occurence of a string within a string.

I was looking for the equivalent of Java’s lastIndexOf(). I couldn’t find it so I wrote this:

Источник

Изучаем PHP: поиск символа в строке

В этой статье рассматриваются различные методы поиска слова, символа или подстроки в тексте. Описываются преимущества и недостатки каждого метода.

Поиск символа в строке — использование strpos() для регистрозависимого поиска

Простейшим способом проверить, содержит ли строка определённое слово, является использование PHP функции strpos(). Она возвращает позицию первого вхождения подстроки в строке или FALSE, если соответствия не найдены. Поэтому можно сравнить значение, возвращаемое функцией strpos() с FALSE, чтобы проверить наличие подстроки. Пример:

При поиске целого слова (например, “на”) функция также вернёт значение TRUE, если строка содержит такие слова, как “она”, “вена” или “например”.

Поиск символа в строке — использование функции stripos() для регистронезависимого поиска

Для регистрозависимого поиска можно использовать функцию stripos(). Она работает аналогично функции strpos(). Единственное отличие заключается в том, что она игнорирует регистр при поиске подстроки внутри другой строки.

Функция strpos() вернула бы значение FALSE во всех перечисленных выше случаях. Но функция stripos() проигнорировала регистр и вернула значение TRUE.

Другим способом поиска, независящим от регистра, является преобразование всех строк и подстрок в одинаковый регистр, используя функции strtolower() и strtoupper(). Для проверки можно использовать strpos(). Но проще stripos().

Поиск символа в строке — использование регулярных выражений

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

Но помните, что функция strpos() работает в три раза быстрее, чем регулярные выражения. Следующий пример демонстрирует, как с их помощью найти слово, символ в строке:

Использование функции preg_match() имеет смысл только при сложном поиске. Например, для проверки того, содержит ли строка слова с десятью и более символами и т.п. Пример:

Чтобы сделать поиск регистронезависимым, добавьте флаг i в конец шаблона. Пример реализации:

Использование регулярных выражений для поиска точного вхождения слова

Функции strpos() и stripos()работают быстрее, чем регулярные выражения. Но их использование для поиска точного вхождения слова может быть проблематичным.

В подобных ситуациях лучше применять регулярные выражения. Можно использовать выражение b в шаблоне регулярного выражения, чтобы обозначить границу слова. Если слово, которое вы ищете, заключено в выражения b, функция preg_match() найдёт только точные вхождения слова и вернет FALSE для частичных совпадений. Вот пример:

Использование strstr() для поиска подстроки

PHP функция strstr() может быть использована для проверки вхождения символа или подстроки. Она возвращает часть исходной строки, начиная с первого вхождения искомого слова и до конца. Функция вернёт значение FALSE, если подстрока не найдена. Благодаря этому можно проверить, содержит ли строка подстроку. Вот пример:

Для регистронезависимого поиска используйте функцию stristr().

Пожалуйста, оставляйте ваши комментарии по текущей теме материала. Мы крайне благодарны вам за ваши комментарии, подписки, отклики, лайки, дизлайки!

Источник

Поиск подстроки в строке в PHP. Проверка строки на символы

В некоторых случаях возникает необходимость найти подстроку в строке, используя встроенные возможности языка программирования PHP. Чтобы решить эту задачу, можно использовать разные инструменты.

Поиск подстроки в строке с помощью strpos

Таким образом, PHP-функция возвращает нам или порядковый номер 1-го символа подстроки в исходной строке, или false, если ничего не найдено.

Применяя эту функцию, учтите, что она может вернуть вам в качестве результата 0 — в таком случае можно говорить, что подстрока находится в самом начале нашей исходной строки. Именно поэтому следует применять троекратный знак равно, о котором упомянуто в коде ($pos === false). Это нужно для проверки успешности поиска.

Поиск подстроки в строке с помощью stripos

Эта функция является регистронезависимым аналогом strpos. Она пригодится, если захотите найти последнее вхождение подстроки. Кстати, регистронезависимый вариант есть и у неё — strripos.

Используем для поиска PHP-функцию preg_match

Данная функция позволит выполнить поиск подстроки, задействуя регулярное выражение. Напомним, что регулярное выражение представляет собой шаблон, сравниваемый со строкой. При этом под один шаблон порой подходят сразу много разных строк.

Регулярные выражения пригодятся, если надо выполнять поиск и проверку не по конкретной подстроке, а требуется обнаружить все строки, которые обладают свойствами, описанными посредством регулярных выражений. Вообще, по правде говоря, знание данной темы заметно расширит ваши возможности и облегчит работу со строками.

Остаётся добавить, что язык программирования PHP располагает богатейшим выбором функций для работы с регулярными выражениями. Это раз. Что касается нашей основной темы, то нельзя не сказать, что для работы со строками в PHP тоже есть огромное количество функций, знакомиться с которыми лучше в официальной документации.

Если же хотите прокачать свои навыки PHP-разработки под руководством практикующих экспертов, добро пожаловать на специальный курс в OTUS!

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *