поиск строки в строке php
Изучаем 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().
Пожалуйста, оставляйте ваши комментарии по текущей теме материала. Мы крайне благодарны вам за ваши комментарии, подписки, отклики, лайки, дизлайки!
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.
stripos
stripos — Возвращает позицию первого вхождения подстроки без учёта регистра
Описание
Список параметров
Строка, в которой производится поиск.
Заметьте, что needle может содержать строку из одного или более символов.
Если этот параметр указан, то поиск будет начат с указанного количества символов с начала строки. Если задано отрицательное значение, отсчёт позиции начала поиска будет произведён с конца строки.
Возвращаемые значения
Возвращает позицию, в которой находится искомая строка, относительно начала строки haystack (независимо от смещения (offset)). Также обратите внимание на то, что позиция строки отсчитывается от 0, а не от 1.
Список изменений
Примеры
Пример #1 Пример использования stripos()
= ‘a’ ;
$mystring1 = ‘xyz’ ;
$mystring2 = ‘ABC’ ;
Примечания
Замечание: Эта функция безопасна для обработки данных в двоичной форме.
Смотрите также
User Contributed Notes 8 notes
I found myself needing to find the first position of multiple needles in one haystack. So I wrote this little function:
Regarding the function by spam at wikicms dot org
It is very bad practice to use the same function name as an existing php function but have a different output format. Someone maintaining the code in the future is likely to be very confused by this. It will also be hard to eradicate from a codebase because the naming is identical so each use of stripos() would have to be analyzed to see how it is expecting the output format (bool or number/bool).
Calling it string_found() or something like that would make a lot more sense for long-term use.
Finding numbers in strings requires you to cast the number to string first.
A handy function if you need to adjust layout based on whether or not a string contains descending letters:
If you like using ternary operator, I wrote simple example how to use stripos function.
Also, in my example I add «How to use namespaces» for wide knowledges for newbies.
this would to work with any language, i hope.
tested on czech (eastern europe) lang.
Поиск подстроки в строке в PHP. Проверка строки на символы
В некоторых случаях возникает необходимость найти подстроку в строке, используя встроенные возможности языка программирования PHP. Чтобы решить эту задачу, можно использовать разные инструменты.
Поиск подстроки в строке с помощью strpos
Таким образом, PHP-функция возвращает нам или порядковый номер 1-го символа подстроки в исходной строке, или false, если ничего не найдено.
Применяя эту функцию, учтите, что она может вернуть вам в качестве результата 0 — в таком случае можно говорить, что подстрока находится в самом начале нашей исходной строки. Именно поэтому следует применять троекратный знак равно, о котором упомянуто в коде ($pos === false). Это нужно для проверки успешности поиска.
Поиск подстроки в строке с помощью stripos
Эта функция является регистронезависимым аналогом strpos. Она пригодится, если захотите найти последнее вхождение подстроки. Кстати, регистронезависимый вариант есть и у неё — strripos.
Используем для поиска PHP-функцию preg_match
Данная функция позволит выполнить поиск подстроки, задействуя регулярное выражение. Напомним, что регулярное выражение представляет собой шаблон, сравниваемый со строкой. При этом под один шаблон порой подходят сразу много разных строк.
Регулярные выражения пригодятся, если надо выполнять поиск и проверку не по конкретной подстроке, а требуется обнаружить все строки, которые обладают свойствами, описанными посредством регулярных выражений. Вообще, по правде говоря, знание данной темы заметно расширит ваши возможности и облегчит работу со строками.
Остаётся добавить, что язык программирования PHP располагает богатейшим выбором функций для работы с регулярными выражениями. Это раз. Что касается нашей основной темы, то нельзя не сказать, что для работы со строками в PHP тоже есть огромное количество функций, знакомиться с которыми лучше в официальной документации.
Если же хотите прокачать свои навыки PHP-разработки под руководством практикующих экспертов, добро пожаловать на специальный курс в OTUS!
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: