php find substring in string
Изучаем 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().
Пожалуйста, оставляйте ваши комментарии по текущей теме материала. Мы крайне благодарны вам за ваши комментарии, подписки, отклики, лайки, дизлайки!
Поиск строк с помощью функций strpos / stripos: 4 примера
Функция PHP strpos используется для поиска подстроки в заданной строке. Она возвращает числовое значение первого вхождения заданной на поиск подстроки.
Синтаксис для использования strpos
PHP функция strpos используется следующим образом:
Примечание: При поиске с помощью функции strpos регистр имеет значение. Так что поиск по ключевым словам “Test” и “test” даст различные результаты.
На примере демо-версий я продемонстрирую использование этой функции для поиска заданной подстроки и вводимого пользователем значения.
Простой пример использования функции strpos
Посмотрите следующий пример, в котором я использовал заданные для поиска значения, чтобы продемонстрировать работу функции strpos PHP :
Посмотреть онлайн демо-версию и код
Код PHP
strpos PHP пример
Пример использования strpos для поиска вводимого пользователем термина
Этот метод может оказаться полезным в определенных сценариях. Например, когда в форму не разрешается вводить определенные слова.
Кроме этого можно проверить, содержится ли слово, заданное пользователем на поиск, в исходной строке. Исходя из этого, можно вывести определенные результаты в виде ответа.
В этой демо-версии, пользователь может ввести термин в текстовое поле. После нажатия кнопки запускается функция strpos, чтобы проверить, содержит ли исходная строка подстроку. На экран будет выводиться соответствующее сообщение:
Для демо-версии я использовал следующую исходную строку:
Для этого был использован следующий пример PHP strpos utf 8 :
Также можете посмотреть разметку strpos PHP примера:
Полную версию можно увидеть в исходном коде страницы демо-версии.
Кроме этого вы можете использовать в качестве источника базу данных для создания системы поиска на своем сайте.
Поиск без учета регистра с помощью функции stripos
Синтаксис почти такой же, как для strpos :
Пример использования функции stripos
В этой демо-версии источником для поиска является следующая строка:
Несмотря на то, что в исходной строке используется заглавная буква, посмотрите, какой будет результат:
Посмотреть онлайн демо-версию и код
Пример с вводимым пользователем поисковым термином
Посмотреть онлайн демо-версию и код
По сравнению с приведенным выше примером использования функции strpos PHP изменена только следующая строка кода:
Пожалуйста, оставляйте свои комментарии по текущей теме статьи. Мы крайне благодарны вам за ваши комментарии, дизлайки, отклики, лайки, подписки!
How to find a substring of a string in an array PHP
If you look at many of my questions, you will see that sometimes I don’t ask the best questions or I am in such a rush that I don’t see the answer that is right in front of me the whole time. If this is another one of those questions, please be kind as some other people haven’t been the nicest. Now onto the question.
I have been in the process of creating a file listing viewer type thing for the past week or so. At this point, its all great but I needed to add a search function. I did so by using array_search(). The only problem is that this function requires you to put in the EXACT name of the file rather than part of it.
Here is the problem. I have tried numerous solutions, and to be frank, my PHP skills aren’t the most professional. I have tried for array_filters and for loops with strpos. Nothing at this point works. My code is below:
Currently there are over 2,000 files and they have all sorts of random characters in them. These characters range from dashes to exclamation marks to letters and numbers as well as periods and many more. I don’t have control over these file names and they have to stay exactly the same.
If you look at the code, I first get all the file names and store them in an array,
Then I check if the search parameter is supplied in the url,
After that, if it is supplied, I will search for it (this is where the problem is). If it isn’t supplied, I simply get the file names from the array and check if they are an image. If they are, I print them all out at the bottom of the page in the form of thumbnails and make their link at the top a page link that scrolls you down to the location of the image. If it isn’t an image, it takes you directly to the file. Note that the thumbnails are links to the actual image.
What is supposed to happen when it searches is that basically does what it would do if it weren’t searching, but it limits itself to files that contain the string «foobar» for example.
When it searches but doesn’t find anything, it prints out that it didn’t find anything and that the user should search again.
If anyone could help with this, it would be greatly appreciated. Like I said at the beginning, please be kind if its a dumb mistake.
Best Regards, Emanuel
EDIT: This article now obviously has an answer and for those finding this article on Google or what have you, I want you to read the comments in the answer post as well as the answer as they provide KEY information!!
strpos
(PHP 4, PHP 5, PHP 7, PHP 8)
strpos — Find the position of the first occurrence of a substring in a string
Description
Find the numeric position of the first occurrence of needle in the haystack string.
Parameters
The string to search in.
Prior to PHP 8.0.0, if needle is not a string, it is converted to an integer and applied as the ordinal value of a character. This behavior is deprecated as of PHP 7.3.0, and relying on it is highly discouraged. Depending on the intended behavior, the needle should either be explicitly cast to string, or an explicit call to chr() should be performed.
If specified, search will start this number of characters counted from the beginning of the string. If the offset is negative, the search will start this number of characters counted from the end of the string.
Return Values
Returns the position of where the needle exists relative to the beginning of the haystack string (independent of offset). Also note that string positions start at 0, and not 1.
Returns false if the needle was not found.
Changelog
Version | Description |
---|---|
8.0.0 | Passing an int as needle is no longer supported. |
7.3.0 | Passing an int as needle has been deprecated. |
7.1.0 | Support for negative offset s has been added. |
Examples
Example #1 Using ===
Example #3 Using an offset
Notes
See Also
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:
strrpos
(PHP 4, PHP 5, PHP 7, PHP 8)
strrpos — Find the position of the last occurrence of a substring in a string
Description
Find the numeric position of the last occurrence of needle in the haystack string.
Parameters
The string to search in.
Prior to PHP 8.0.0, if needle is not a string, it is converted to an integer and applied as the ordinal value of a character. This behavior is deprecated as of PHP 7.3.0, and relying on it is highly discouraged. Depending on the intended behavior, the needle should either be explicitly cast to string, or an explicit call to chr() should be performed.
This is effectively looking for the last occurrence of needle before the last offset bytes.
Return Values
Returns the position where the needle exists relative to the beginning of the haystack string (independent of search direction or offset).
Note: String positions start at 0, and not 1.
Returns false if the needle was not found.
Changelog
Version | Description |
---|---|
8.0.0 | Passing an int as needle is no longer supported. |
7.3.0 | Passing an int as needle has been deprecated. |
Examples
Example #1 Checking if a needle is in the haystack
It is easy to mistake the return values for «character found at position 0» and «character not found». Here’s how to detect the difference:
Example #2 Searching with offsets
The above example will output:
See Also
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: