php содержание подстроки в строке

Поиск строк с помощью функций strpos / stripos: 4 примера

Функция PHP strpos используется для поиска подстроки в заданной строке. Она возвращает числовое значение первого вхождения заданной на поиск подстроки.

Синтаксис для использования strpos

PHP функция strpos используется следующим образом:

Примечание: При поиске с помощью функции strpos регистр имеет значение. Так что поиск по ключевым словам “Test” и “test” даст различные результаты.

На примере демо-версий я продемонстрирую использование этой функции для поиска заданной подстроки и вводимого пользователем значения.

Простой пример использования функции strpos

Посмотрите следующий пример, в котором я использовал заданные для поиска значения, чтобы продемонстрировать работу функции strpos PHP :

php содержание подстроки в строке. Смотреть фото php содержание подстроки в строке. Смотреть картинку php содержание подстроки в строке. Картинка про php содержание подстроки в строке. Фото php содержание подстроки в строке

Посмотреть онлайн демо-версию и код

Код PHP

strpos PHP пример

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

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

Кроме этого можно проверить, содержится ли слово, заданное пользователем на поиск, в исходной строке. Исходя из этого, можно вывести определенные результаты в виде ответа.

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

php содержание подстроки в строке. Смотреть фото php содержание подстроки в строке. Смотреть картинку php содержание подстроки в строке. Картинка про php содержание подстроки в строке. Фото php содержание подстроки в строке

Для демо-версии я использовал следующую исходную строку:

Для этого был использован следующий пример PHP strpos utf 8 :

Также можете посмотреть разметку strpos PHP примера:

Полную версию можно увидеть в исходном коде страницы демо-версии.

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

Поиск без учета регистра с помощью функции stripos

Синтаксис почти такой же, как для strpos :

Пример использования функции stripos

В этой демо-версии источником для поиска является следующая строка:

Несмотря на то, что в исходной строке используется заглавная буква, посмотрите, какой будет результат:

Посмотреть онлайн демо-версию и код

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

Посмотреть онлайн демо-версию и код

По сравнению с приведенным выше примером использования функции strpos PHP изменена только следующая строка кода:

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

Источник

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

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

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

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

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

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

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

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

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

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

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

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

Источник

Функции для работы со строками

Для получения информации о более сложной обработке строк обратитесь к функциями Perl-совместимых регулярных выражений. Для работы с многобайтовыми кодировками посмотрите на функции по работе с многобайтовыми кодировками.

Содержание

User Contributed Notes 24 notes

In response to hackajar yahoo com,

No string-to-array function exists because it is not needed. If you reference a string with an offset like you do with an array, the character at that offset will be return. This is documented in section III.11’s «Strings» article under the «String access and modification by character» heading.

I’m converting 30 year old code and needed a string TAB function:

//tab function similar to TAB used in old BASIC languages
//though some of them did not truncate if the string were
//longer than the requested position
function tab($instring=»»,$topos=0) <
if(strlen($instring)

I use these little doo-dads quite a bit. I just thought I’d share them and maybe save someone a little time. No biggy. 🙂

Just a note in regards to bloopletech a few posts down:

The word «and» should not be used when converting numbers to text. «And» (at least in US English) should only be used to indicate the decimal place.

Example:
1,796,706 => one million, seven hundred ninety-six thousand, seven hundred six.
594,359.34 => five hundred ninety four thousand, three hundred fifty nine and thirty four hundredths

/*
* example
* accept only alphanum caracteres from the GET/POST parameters ‘a’
*/

to: james dot d dot baker at gmail dot com

PHP has a builtin function for doing what your function does,

/**
Utility class: static methods for cleaning & escaping untrusted (i.e.
user-supplied) strings.

Any string can (usually) be thought of as being in one of these ‘modes’:

pure = what the user actually typed / what you want to see on the page /
what is actually stored in the DB
gpc = incoming GET, POST or COOKIE data
sql = escaped for passing safely to RDBMS via SQL (also, data from DB
queries and file reads if you have magic_quotes_runtime on—which
is rare)
html = safe for html display (htmlentities applied)

Always knowing what mode your string is in—using these methods to
convert between modes—will prevent SQL injection and cross-site scripting.

This class refers to its own namespace (so it can work in PHP 4—there is no
self keyword until PHP 5). Do not change the name of the class w/o changing
all the internal references.

Example usage: a POST value that you want to query with:
$username = Str::gpc2sql($_POST[‘username’]);
*/

Example: Give me everything up to the fourth occurance of ‘/’.

//
// string strtrmvistl( string str, [int maxlen = 64],
// [bool right_justify = false],
// [string delimter = «
\n»])
//
// splits a long string into two chunks (a start and an end chunk)
// of a given maximum length and seperates them by a given delimeter.
// a second chunk can be right-justified within maxlen.
// may be used to ‘spread’ a string over two lines.
//

I really searched for a function that would do this as I’ve seen it in other languages but I couldn’t find it here. This is particularily useful when combined with substr() to take the first part of a string up to a certain point.

?>

Example: Give me everything up to the fourth occurance of ‘/’.

The functions below:

Are correct, but flawed. You’d need to use the === operator instead:

Here’s an easier way to find nth.

I was looking for a function to find the common substring in 2 different strings. I tried both the mb_string_intersect and string_intersect functions listed here but didn’t work for me. I found the algorithm at http://en.wikibooks.org/wiki/Algorithm_implementation/Strings/Longest_common_substring#PHP so here I post you the function

Here’s a simpler «simplest» way to toggle through a set of 1..n colors for web backgrounds:

If you want a function to return all text in a string up to the Nth occurrence of a substring, try the below function.

(Pommef provided another sample function for this purpose below, but I believe it is incorrect.)

/*
// prints:
S: d24jkdslgjldk2424jgklsjg24jskgldjk24
1: d
2: d24jkdslgjldk
3: d24jkdslgjldk24
4: d24jkdslgjldk2424jgklsjg
5: d24jkdslgjldk2424jgklsjg24jskgldjk
6: d24jkdslgjldk2424jgklsjg24jskgldjk24
7: d24jkdslgjldk2424jgklsjg24jskgldjk24
*/

?>

Note that this function can be combined with wordwrap() to accomplish a routine but fairly difficult web design goal, namely, limiting inline HTML text to a certain number of lines. wordwrap() can break your string using
, and then you can use this function to only return text up to the N’th
.

You will still have to make a conservative guess of the max number of characters per line with wordwrap(), but you can be more precise than if you were simply truncating a multiple-line string with substr().

= ‘Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Pellentesque id massa. Duis sollicitudin ipsum vel diam. Aliquam pulvinar sagittis felis. Nullam hendrerit semper elit. Donec convallis mollis risus. Cras blandit mollis turpis. Vivamus facilisis, sapien at tincidunt accumsan, arcu dolor suscipit sem, tristique convallis ante ante id diam. Curabitur mollis, lacus vel gravida accumsan, enim quam condimentum est, vitae rutrum neque magna ac enim.’ ;

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Pellentesque id massa. Duis sollicitudin
ipsum vel diam. Aliquam pulvinar sagittis felis. Nullam hendrerit semper elit. Donec convallis
mollis risus. Cras blandit mollis turpis. Vivamus facilisis, sapien at tincidunt accumsan, arcu

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Pellentesque id massa. Duis sollicitudin
ipsum vel diam. Aliquam pulvinar sagittis felis. Nullam hendrerit semper elit. Donec convallis
mollis risus. Cras blandit mollis turpis. Vivamus facilisis, sapien at tincidunt accumsan, arcu
dolor suscipit sem, tristique convallis ante ante id diam. Curabitur mollis, lacus vel gravida

Источник

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:

Источник

stristr

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

stristr — Регистронезависимый вариант функции strstr()

Описание

Возвращает всю строку haystack начиная с первого вхождения needle включительно.

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

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

needle и haystack обрабатываются без учёта регистра.

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

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

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

Примеры

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

Пример #2 Проверка на вхождение строки

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

Примечания

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

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

User Contributed Notes 8 notes

There was a change in PHP 4.2.3 that can cause a warning message
to be generated when using stristr(), even though no message was
generated in older versions of PHP.

Just been caught out by stristr trying to converting the needle from an Int to an ASCII value.

Got round this by casting the value to a string.

An example for the stristr() function:

I think there is a bug in php 5.3 in stristr with uppercase Ä containing other character

if you search only with täry it works, but as soon as the word is tärylä it does not. TÄRYL works fine

handy little bit of code I wrote to take arguments from the command line and parse them for use in my apps.

//now lets parse the array and return the parameter name and its setting
// since the input is being sent by the user via the command line
//we will use stristr since we don’t care about case sensitivity and
//will convert them as needed later.

//lets grap the parameter name first using a double reverse string
// to get the begining of the string in the array then reverse it again
// to set it back. we will also «trim» off the «=» sign

//now lets get what the parameter is set to.
// again «trimming» off the = sign

// now do something with our results.
// let’s just echo them out so we can see that everything is working

?>

when run from the CLI this script returns the following.

Array index is 0 and value is a.php
Parameter is and is set to

Array index is 1 and value is val1=one
Parameter is val1 and is set to one

Array index is 2 and value is val2=two
Parameter is val2 and is set to two

Array index is 3 and value is val3=three
Parameter is val3 and is set to three

Источник

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

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