(.*?)

Searching Strings in PHP

When writing PHP scripts, you often need to search a string for a particular chunk of text. For example, you might be writing a search engine to search through pages of content, or you might want to know if a URL or email address contains a certain domain name.

PHP gives you many useful functions for searching strings. In this article you look at:

  • strstr() for finding out whether some text is in a string
  • strpos() and strrpos() for finding the position of some text in a string
  • substr_count() for finding out how many times some text appears in a string

Simple text searching with strstr()

PHP’s strstr() function simply takes a string to search, and a chunk of text to search for. If the text was found, it returns the portion of the string from the first character of the match up to the end of the string:

 $myString = 'Hello, there!'; echo strstr( $myString, 'llo' ); // Displays "llo, there!" 

If the text wasn’t found then strstr() returns false . You can use this fact to determine if the text chunk was in the string or not:

 $myString = 'Hello, there!'; if ( strstr( $myString, 'Goodbye' ) ) < echo "Text found"; >else

strstr() is — for example, «hello» won’t match «Hello» . If you don’t care about matching case, use the case-insensitive version, stristr() , instead.

Читайте также:  Http header accept javascript

Finding the position of a match: strpos() and strrpos()

strpos() takes the same 2 arguments as strstr() . However, rather than returning a portion of the string, it returns the index of the first character of the matched text in the string:

 $myString = 'Hello, there!'; echo strpos( $myString, 'llo' ); // Displays "2" 

In the above code, strpos() finds the text ‘llo’ in the target string starting at the 3rd character, so it returns 2 . (Remember that character index positions in strings start from 0, not 1.)

Be careful when using strpos() to check for the existence of a match. The following code incorrectly displays “Not found”, because strpos() returns 0 , which is equivalent to false in PHP:

 $myString = 'Hello, there!'; if ( strpos( $myString, 'Hello' ) ) < echo "Found"; >else

To fix this, make sure you test explicitly for false by using the === or !== operator. The following code correctly displays “Found”:

 $myString = 'Hello, there!'; if ( strpos( $myString, 'Hello' ) !== false ) < echo "Found"; >else

You can pass a third argument to strpos() to specify the index position from which to begin the search:

 $myString = 'Hello, there!'; echo strpos( $myString, 'e' ) . '
'; // Displays "1" echo strpos( $myString, 'e', 2 ) . '
'; // Displays "9"

The strrpos() function is very similar to strpos() . The only difference is that it finds the last match in the string instead of the first:

 $myString = 'Hello, there!'; echo strpos( $myString, 'e' ) . "
"; // Displays "1" echo strrpos( $myString, 'e' ) . "
"; // Displays "11"

As with strstr() , the strpos() and strrpos() functions are case sensitive. Their case-insensitive equivalents are stripos() and strripos() respectively.

Counting matches with substr_count()

You can use PHP’s substr_count() function to find the number of times a chunk of text appears in the target string:

 $myString = 'Short stories'; echo substr_count( $myString, 'or' ); // Displays "2" 

As with strpos() and strrpos() , you can pass an optional third argument: the index position to begin the search. For example:

 $myString = 'Short stories'; echo substr_count( $myString, 'or', 6 ); // Displays "1" 

You can also pass an optional fourth argument: the number of characters after the offset position in which to search for the text. For example:

 echo substr_count( $myString, 'or', 0, 10 ) . '
'; // Displays "2" echo substr_count( $myString, 'or', 0, 5 ) . '
'; // Displays "1"

In this article you’ve looked at how to search strings in PHP. You’ve explored the strstr() function for finding out whether a chunk of text exists in a string; strpos() and strrpos() for locating text in a string; and substr_count() for finding out the number of matches in a string. Happy coding!

Reader Interactions

Comments

This is my case: Mysql Column called TAG Containing this information: row1 Note: bla bla bla1 – Tag: bla bla bla1
row2 Note: bla bla bla2 – Tag: bla bla bla2
row3 Note: bla bla bla3 – Tag: bla bla bla3
row4 Tag: bla bla bla4
row5 Note: bla bla bla4 So I want to do a query with php that displays the all rows, but from column TAG display the info containing only the string corresponding to “Note: bla bla blaX”
so in the row 4 shouldn’t show anything but at the others rows should show the corresponding Note. I hope it is not too difficult. Thanks for your help.

You’ll probably want to trim any whitespace from the end of the match too. It’s a pretty nasty data format – you’d be better off having your notes and tags in separate columns in the DB, if possible.

Thanks for your answer, the problem is I can not use a different colum, that’s why I’m looking for a solution like this, actually to make it easier may be I can use tags, I mean something like thiis: Row Stuff Info
row1 First Stuff bla bla bla1bla bla bla1
row2 Second Stuff bla bla bla2bla bla bla2
row3 Third Stuff bla bla bla3bla bla bla3
row4 Fourth Stuff bla bla bla1
row5 Fifth Stuff bla bla bla1 And make the regular expression accordingly
I will try your solution and I let you know how it goes.
Thanks again. [Edited by achandia on 11-Nov-10 02:29]

$rowtag = $row['Tag']; $resulttag = preg_match( "/(.*)/", $rowtag, $matches ); echo $matches[1]. "";

Yes, that is a better data format. You want to use delimiters that will never be seen in the data. Glad you solved it 🙂 Cheers,
Matt

A very useful article. Thank you. I found that strstr() also takes a true or false argument.
If set to true, it will return the part of the string before the first occurrence of the match: $string = ‘Hello, there!’;
$outstring = strstr($string, ‘llo’, true);
echo $outstring; // Displays ‘He’

Leave a Reply Cancel reply

To include a block of code in your comment, surround it with

.

tags. You can include smaller code snippets inside some normal text by surrounding them with . tags.

Allowed tags in comments: .

Primary Sidebar

Hire Matt!

Matt Doyle headshot

Need a little help with your website? I have over 20 years of web development experience under my belt. Let’s chat!

Matt Doyle - Codeable Expert Certificate

Stay in Touch!

Subscribe to get a quick email whenever I add new articles, free goodies, or special offers. I won’t spam you.

Recent Posts

Источник

Поиск в строке PHP

Поиск в строке PHP

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

Поиск с помощью функции strstr()

strstr() — находит первое вхождение подстроки.

Поиск с помощью функции strpos()

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

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

preg_match() — выполняет проверку на соответствие регулярному выражению.

hello php! content'; if (preg_match("!!si", $html, $matches)) < echo $matches[1]; >else < echo "Тег не найден"; >?>

Если вам понравилась статья, вы можете отблагодарить автора любой суммой, какую сочтете для себя приемлемой:

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

Подборка бесплатных IT-курсов и вебинаров от Skillbox.

Бесплатные IT-курсы, нужно только пройти онлайн-тест здесь

На сегодняшний день Яндекс.Касса — это один из самых популярных мерчантов для подключения оплаты на любом сайте. Касса позволяет принимать платежи с помощью банковских карт и Яндекс.Денег, а так же подключить онлайн-кассу. Если у вас интернет-магазин на одной из популярных Читать далее

В этом руководстве создадим чат-бота ВКонтакте, которого можно добавить не только в сообщения группы, но и в групповую беседу. Бот может прослушивать все сообщения в беседе, и если в каком-то из них будет содержаться определенное слово, фраза или часть текста, Читать далее

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

Абсолютно любой предмет из нашей жизни мы можем описать по его характеристикам и состоянию, а так же воздействовать на это состояние. Например, ваш автомобиль имеет определенный цвет, марку, двигатель и т.д. Кроме того он может ехать, стоять, набирать или сбавлять Читать далее

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

В этой статье рассмотрим как создать простого чат-бота для Viber, который будет принимать и отправлять сообщения в чат. Шаг 1 Итак, для начала необходимо зарегистрироваться в сервисе Viber Admin Panel по этой ссылке. Шаг 2 Создаём бота. Для этого заполняем Читать далее

Источник

PHP Search String | Searching Strings for Substrings in PHP

PHP Search String

In this article, I will discuss the PHP search string, Sometimes in PHP, when you writing the script, you often need to search a string for a particular chunk of text. there are several functions that PHP provides for search one string within another. furthermore, some return the location of the found string.
(strrpos, strpos and some related) and other return parts of the original string. therefore, In PHP search string, if the string which you are searching. for is not found within original then The search functions return false. suppose that if you simply determine whether one string exists within another, then the most efficient option is strpos.
consider an example, you want to write a search engine to search through pages of content, or you want to know if an email address or URL contains a certain domain name. For PHP Search String, I will discuss all functions, look at:-

Important Note:
strstr() function used for finding out whether some text is in the string.
strrpos() and strpos() function used for finding the position of some text in a string.
substr_count() function is used for finding out how many times some text appears in a string.

PHP Search String: Simple text searching with strstr()

The strstr function simply takes a string to search and a chunk of text to search for. the first string
the argument for the second, if the second is found within the first, strstr returns the portion of the
original string starting from the first found occurrence to the end of the string.

Источник

Оцените статью