Автоматический подбор ключевых слов для текста на php. Мета-теги для поисковых систем в HTML Но почему многие по-прежнему используют keywords
При работе автоматических парсеров, возникает естественная необходимость подобрать к тексту его ключевые слова. Это необходимо для поисковой оптимизации статьи.
К примеру мы спарсили объявление с доски, в нем продается Apple Iphone 4s, подержанный. Небольшой текст описания с характеристиками и цена.
Из этого текста необходимо выделить ключевые слова. Заполнять их при автоматическом парсинге будет накладно. Поэтому нужно использовать скрипты для выборки ключевых слов.
Для начала, нужно составить список всех слов употребляемых в тексте, с сортировкой по частоте их употребления. Откинув короткие слова (меньше 5-ти знаков) и различные вспомогательные части речи, типа местоимений и наречий.
Когда-то давно, для разработки сайтов я использовал Danneo CMS. Так вот, в ней была великолепная функция выделения ключевых слов в тексте. Только ради этого, скачал новую версию Danneo, она кстати обновилась до версии 0.5.5
Вот эта функиця
Function seokeywords($contents,$symbol=5,$words=35){ $contents = @preg_replace(array(""<[\/\!]*?[^<>]*?>"si",""([\r\n])[\s]+"si",""&{1,6};"si",""(+)"si"), array("","\\1 "," "," "),strip_tags($contents)); $rearray = array("~","!","@","#","$","%","^","&","*","(",")","_","+", "`",""","№",";",":","?","-","=","|","\"","\\","/", "[","]","{","}",""",",",".","<",">","\r\n","\n","\t","«","»"); $adjectivearray = array("ые","ое","ие","ий","ая","ый","ой","ми","ых","ее","ую","их","ым", "как","для","что","или","это","этих", "всех","вас","они","оно","еще","когда", "где","эта","лишь","уже","вам","нет", "если","надо","все","так","его","чем", "при","даже","мне","есть","только","очень", "сейчас","точно","обычно"); $contents = @str_replace($rearray," ",$contents); $keywordcache = @explode(" ",$contents); $rearray = array(); foreach($keywordcache as $word){ if(strlen($word)>=$symbol && !is_numeric($word)){ $adjective = substr($word,-2); if(!in_array($adjective,$adjectivearray) && !in_array($word,$adjectivearray)){ $rearray[$word] = (array_key_exists($word,$rearray)) ? ($rearray[$word] + 1) : 1; } } } @arsort($rearray); $keywordcache = @array_slice($rearray,0,$words); $keywords = ""; foreach($keywordcache as $word=>$count){ $keywords.= ",".$word; } return substr($keywords,1); }
из выше набранного текста функция выдает вот такой набор
Array,rearray,contents,keywordcache,слова,keywords,слов,adjectivearray,symbol,replace,words,этого,вот,
Danneo,тексте,функция,нужно,ключевых,foreach,текста,ключевые,substr,необходимо,adjective,выдает,
была,великолепная,выделения,скачал,ради,Только,ней,набранного,набор,давно
не плохо ни правда ли?!
Дальше, можно поступить следующим образом: просеять все эти слова по базе заведомо подготовленных ключевиков. И оставить только нужные. У меня такая база создавалась несколько лет вручную. Это база тегов, которыми подкрепляется каждая статья.
Так по ключевым словам можно легко восстановить информацию о статье. Т.е. поисковик будет иметь конкретное представление о том, что содержим Ваша страница. Подобно тому, как
I have title (varchar), description (text), keywords (varchar) fields in my mysql table.
I kept keywords field as I thought I would be searching in this field only. But I now require to search among all three fields. so for keywords "word1 word2 word3", my query becomes
SELECT * FROM myTable WHERE (name LIKE "%word1%" OR description LIKE "%word1%" OR keywords LIKE "%word1%" OR name LIKE "%word2%" OR description LIKE "%word2%" OR keywords LIKE "%word2%" OR name LIKE "%word3%" OR description LIKE "%word3%" OR keywords LIKE "%word3%") AND status = "live"
Looks a bit messy but this works. But now I need to implement synonym search. so for a given word assuming there are a few synonyms available this query becomes more messy as I loop through all of the words. As the requirements are getting clearer, I will need to join this myTable to some other tables as well.
- Is there any other method/technique you can recommend to me?
Do you think the above way is messy and will cause problems as the data grow?
How can I avoid above mess? Is there any cleaner solution I can go by? Any example will help me.
EDIT
@Peter Stuifzand suggested me that I could create one search_index table and store all 3 fields (title,keyword,desc) info on that and do full text search. I understand that additionally this table will include reference to myTable primary key as well.
But my advanced search may include joining mytable with Category table, geographic_location table (for searching within 10, 20 miles etc), filtering by someother criteria and of course, sorting of search results. Do you think using mysql fulltext will not slow it down?
By Ibrahim Diallo
Published Jul 2 2014 ~ 16 minutes readSearch is an important feature on a website. When my few readers want to look for a particular passage on my blog, they use the search box. It used to be powered by Google Search, but I have since then changed it to my own home-brewed version not because I can do better but because it was an interesting challenge.
If you are in a hurry and just want your site to be searchable, well do what I did before, use Google.
// In search.php file $term = isset($_GET["query"])?$_GET["query"]: ""; $term = urlencode($term); $website = urlencode("www.yourwebsite.com"); $redirect = "https://www.google.com/search?q=site%3A{$website}+{$term}"; header("Location: $redirect"); exit;
What it does is pretty simple. Get the term passed by the user, and forward it to Google search page. Limit the search result to our current domain using the site: keyword in the search query. All your pages that are indexed by Google will be available through search now. If you do want to handle your search in house however, then keep reading.
Homemade Search Solution
Before we go any further, try using the search box on this blog. It uses the same process that I will describe below. If you feel that this is what you want then please continue reading.
This solution is catered to small websites. I make use of LIKE with wild cards on both ends, meaning your search cannot be indexed. This means the solution will work fine for your blog or personal website that doesn"t contain tons of data. Port it to a bigger website and it might become very slow. MySQL offers Full Text Search which is not what we are doing here.
Note: If you have 5000 blog posts you are still fine. .
We will take the structure of this blog as a reference. Each blog post has:
- A title p_title
- A url p_url
- A summary p_summary
- A post content p_content
- And catergories category.tagname
For every field that matches with our search term, we will give it a score. The score will be based on the importance of the match:
// the exact term matches is found in the title $scoreFullTitle = 6; // match the title in part $scoreTitleKeyword = 5; // the exact term matches is found in the summary $scoreFullSummary = 5; // match the summary in part $scoreSummaryKeyword = 4; // the exact term matches is found in the content $scoreFullDocument = 4; // match the document in part $scoreDocumentKeyword = 3; // matches a category $scoreCategoryKeyword = 2; // matches the url $scoreUrlKeyword = 1;
Before we get started, there are a few words that do not contribute much to a search that should be removed. Example "in","it","a","the","of" ... . We will filter those out and feel free to add any word you think is irrelevant. Another thing is, we want to limit the length of our query. We don"t want a user to write a novel in the search field and crash our MySQL server.
// Remove unnecessary words from the search term and return them as an array function filterSearchKeys($query){ $query = trim(preg_replace("/(\s+)+/", " ", $query)); $words = array(); // expand this list with your words. $list = array("in","it","a","the","of","or","I","you","he","me","us","they","she","to","but","that","this","those","then"); $c = 0; foreach(explode(" ", $query) as $key){ if (in_array($key, $list)){ continue; } $words = $key; if ($c >= 15){ break; } $c++; } return $words; } // limit words number of characters function limitChars($query, $limit = 200){ return substr($query, 0,$limit); }
Our helper functions can now limit character count and filter useless words. The way we will implement our algorithm is by giving a score every time we find a match. We will match words using the if statement and accumulate points as we match more words. At the end we can use that score to sort our results
Note: I will not be showing how to connect to MySQL database. If you are having problems to efficiently connect to the database I recommend reading this .
Let"s give our function a structure first. Note I left placeholders so we can implement sections separately.
Function search($query){ $query = trim($query); if (mb_strlen($query)===0){ // no need for empty search right? return false; } $query = limitChars($query); // Weighing scores $scoreFullTitle = 6; $scoreTitleKeyword = 5; $scoreFullSummary = 5; $scoreSummaryKeyword = 4; $scoreFullDocument = 4; $scoreDocumentKeyword = 3; $scoreCategoryKeyword = 2; $scoreUrlKeyword = 1; $keywords = filterSearchKeys($query); $escQuery = DB::escape($query); // see note above to get db object $titleSQL = array(); $sumSQL = array(); $docSQL = array(); $categorySQL = array(); $urlSQL = array(); /** Matching full occurrences PLACE HOLDER **/ /** Matching Keywords PLACE HOLDER **/ $sql = "SELECT p.p_id,p.p_title,p.p_date_published,p.p_url, p.p_summary,p.p_content,p.thumbnail, ((-- Title score ".implode(" + ", $titleSQL).")+ (-- Summary ".implode(" + ", $sumSQL).")+ (-- document ".implode(" + ", $docSQL).")+ (-- tag/category ".implode(" + ", $categorySQL).")+ (-- url ".implode(" + ", $urlSQL).")) as relevance FROM post p WHERE p.status = "published" HAVING relevance >
In the query, all scores will be summed up as the relevance variable and we can use it to sort the results.
Matching full occurrences
We make sure we have some keywords first then add our query.
If (count($keywords) > 1){ $titleSQL = "if (p_title LIKE "%".$escQuery."%",{$scoreFullTitle},0)"; $sumSQL = "if (p_summary LIKE "%".$escQuery."%",{$scoreFullSummary},0)"; $docSQL = "if (p_content LIKE "%".$escQuery."%",{$scoreFullDocument},0)"; }
Those are the matches with higher score. If the search term matches an article that contains these, they will have higher chances of appearing on top.
Matching keywords occurrences
We loop through all keywords and check if they match any of the fields. For the category match, I used a sub-query since a post can have multiple categories.
Foreach($keywords as $key){ $titleSQL = "if (p_title LIKE "%".DB::escape($key)."%",{$scoreTitleKeyword},0)"; $sumSQL = "if (p_summary LIKE "%".DB::escape($key)."%",{$scoreSummaryKeyword},0)"; $docSQL = "if (p_content LIKE "%".DB::escape($key)."%",{$scoreDocumentKeyword},0)"; $urlSQL = "if (p_url LIKE "%".DB::escape($key)."%",{$scoreUrlKeyword},0)"; $categorySQL = "if ((SELECT count(category.tag_id) FROM category JOIN post_category ON post_category.tag_id = category.tag_id WHERE post_category.post_id = p.post_id AND category.name = "".DB::escape($key)."") > 0,{$scoreCategoryKeyword},0)"; }
Also as pointed by a commenter below, we have to make sure that the these variables are not empty arrays or the query will fail.
// Just incase it"s empty, add 0 if (empty($titleSQL)){ $titleSQL = 0; } if (empty($sumSQL)){ $sumSQL = 0; } if (empty($docSQL)){ $docSQL = 0; } if (empty($urlSQL)){ $urlSQL = 0; } if (empty($tagSQL)){ $tagSQL = 0; }
At the end the queries are all concatenated and added together to determine the relevance of the post to the search term.
// Remove unnecessary words from the search term and return them as an array function filterSearchKeys($query){ $query = trim(preg_replace("/(\s+)+/", " ", $query)); $words = array(); // expand this list with your words. $list = array("in","it","a","the","of","or","I","you","he","me","us","they","she","to","but","that","this","those","then"); $c = 0; foreach(explode(" ", $query) as $key){ if (in_array($key, $list)){ continue; } $words = $key; if ($c >= 15){ break; } $c++; } return $words; } // limit words number of characters function limitChars($query, $limit = 200){ return substr($query, 0,$limit); } function search($query){ $query = trim($query); if (mb_strlen($query)===0){ // no need for empty search right? return false; } $query = limitChars($query); // Weighing scores $scoreFullTitle = 6; $scoreTitleKeyword = 5; $scoreFullSummary = 5; $scoreSummaryKeyword = 4; $scoreFullDocument = 4; $scoreDocumentKeyword = 3; $scoreCategoryKeyword = 2; $scoreUrlKeyword = 1; $keywords = filterSearchKeys($query); $escQuery = DB::escape($query); // see note above to get db object $titleSQL = array(); $sumSQL = array(); $docSQL = array(); $categorySQL = array(); $urlSQL = array(); /** Matching full occurences **/ if (count($keywords) > 1){ $titleSQL = "if (p_title LIKE "%".$escQuery."%",{$scoreFullTitle},0)"; $sumSQL = "if (p_summary LIKE "%".$escQuery."%",{$scoreFullSummary},0)"; $docSQL = "if (p_content LIKE "%".$escQuery."%",{$scoreFullDocument},0)"; } /** Matching Keywords **/ foreach($keywords as $key){ $titleSQL = "if (p_title LIKE "%".DB::escape($key)."%",{$scoreTitleKeyword},0)"; $sumSQL = "if (p_summary LIKE "%".DB::escape($key)."%",{$scoreSummaryKeyword},0)"; $docSQL = "if (p_content LIKE "%".DB::escape($key)."%",{$scoreDocumentKeyword},0)"; $urlSQL = "if (p_url LIKE "%".DB::escape($key)."%",{$scoreUrlKeyword},0)"; $categorySQL = "if ((SELECT count(category.tag_id) FROM category JOIN post_category ON post_category.tag_id = category.tag_id WHERE post_category.post_id = p.post_id AND category.name = "".DB::escape($key)."") > 0,{$scoreCategoryKeyword},0)"; } // Just incase it"s empty, add 0 if (empty($titleSQL)){ $titleSQL = 0; } if (empty($sumSQL)){ $sumSQL = 0; } if (empty($docSQL)){ $docSQL = 0; } if (empty($urlSQL)){ $urlSQL = 0; } if (empty($tagSQL)){ $tagSQL = 0; } $sql = "SELECT p.p_id,p.p_title,p.p_date_published,p.p_url, p.p_summary,p.p_content,p.thumbnail, ((-- Title score ".implode(" + ", $titleSQL).")+ (-- Summary ".implode(" + ", $sumSQL).")+ (-- document ".implode(" + ", $docSQL).")+ (-- tag/category ".implode(" + ", $categorySQL).")+ (-- url ".implode(" + ", $urlSQL).")) as relevance FROM post p WHERE p.status = "published" HAVING relevance > 0 ORDER BY relevance DESC,p.page_views DESC LIMIT 25"; $results = DB::query($sql); if (!$results){ return false; } return $results; }
Now your search.php file can look like this:
$term = isset($_GET["query"])?$_GET["query"]: ""; $search_results = search($term); if (!$search_results) { echo "No results"; exit; } // Print page with results here.
We created a simple search algorithm that can handle a fair amount of content. I arbitrarily chose the score for each match, feel free to tweak it to something that works best for you. And there is always room for improvement.
It is a good idea to track the search term coming from your users, this way you can see if most users search for the same thing. If there is a pattern, then you can save them a trip and just cache the results using Memcached .
If you want to see this search algorithm in action, go ahead and try looking for an article on the search box on top of the page. I have added extra features like returning the part where the match was found in the text. Feel free to add features to yours.
Did you like this article? You can subscribe to read more awesome ones. .
On a related note, here are some interesting articles.
It is time to deal with mysql_* functions once and for all. These methods are deprecated and slow. The time to upgrade has long passed yet we still see it everywhere. Since I cannot force every author to update their tutorial and blogs, I decided to write a post to hopefully rank better and provide the essential information to help new comers.
Making your own website shouldn"t be too difficult. Hosting companies like Godaddy or Hostgator make it super easy for anyone to get started; they allow you to create a whole website without ever writing code. For most people, it is plenty to run a WordPress blog. If this is what you are looking for you should head to Godaddy.com right now. We are done here. But on the other hand, if you want to have control and not be limited by the short comings of a shared hosting without busting your wallet, you have come to the right place.
Vim is my favorite text editor on the terminal. After playing for a little while with nano and emacs , I finally settled with vim for its simplicity (bare with me please). Although it can be customized and used like an entire IDE, I use it mostly for editing files on my servers and making small but crucial changes. Let"s not get into Editor war and get started.
Comments(45)
Zaryel Aug 12 2015:
Ian Mustafa Sep 26 2015:
Rob Sep 29 2015:
adeem Feb 11 2016:
Ivan Venediktov Apr 9 2016.
Meta keywords — список ключевых слов (key words), соответствующих содержимому страницы сайта. Поисковые системы могут использовать ключевые слова тега meta name keywords content при индексации. Однако в отличие от meta description, значение атрибута content тега meta name keywords уже существенно менялось и никто достоверно не может сказать, в какой степени ключевые слова из мета кейвордс используются различными поисковыми системами.
Синтаксис html meta keywords
Мета-тег keywords размещается в html сайта внутри тега .
О том, как стоит правильно заполнять ключевыми словами meta keywords и как не стоит, можно сказать примерно следующее.
Как не стоит заполнять meta keywords:
- не больше 20 слов . Излишнее перечисление ключевых слов вряд ли будет позитивно воспринято поисковыми системами;
- не более 3-х повторов . Многократное повторное перечисление одного и того же ключевого слова (фразы) всегда негативно воспринимается при и определении соответствия страницы поисковым запросам.
Как стоит заполнять meta keywords:
- больше склонений . Если очень хочется использовать ключевое словно мета кейвордс несколько раз — используйте ключевое слово (фразу) в различных склонениях и числах;
- очепятки опечатки . Список ключевых слов можно разбавить популярными опечатками ключевых слов. Иногда опечатки бывают настолько популярными, что отображаются в подсказках прямо в поисковой строке;
- англоязычные запросы . Если на сайте могут быть использованы англоязычные ключевые слова, значение которых соответствует содержимому страницы, почему бы не добавить их в мета тэг кейвордс.
Ключевые слова meta keywords изначально существенно влияли на , что активно пользовались для и его вывода по необходимым ключевым запросам в топ поисковой выдачи. В результате, поисковые системы либо вовсе перестали учитывать meta тег keywords при индексации, либо свели его значение к минимуму.
Как писать ключевые слова в meta keywords — через запятую или через пробел?
Как правильно писать ключевые слова?
— Популярный вопрос.
Через запятую, через пробел, через запятую с пробелами или без пробелов?
- писать ключевые слова через запятую (с пробелом после запятой). Самый популярный вариант написания ключевых слов в meta keywords;
- писать ключевые слова через пробел .
Чтобы определиться, какой вариант лучше, я задам вопрос. Как создать больше всего вариаций ключевых запросов, используя ограниченный набор слов и повторов?
Meta keywords примеры правильного написания ключевых слов
Пример 1 — ключевые слова через запятую :
Плюшевые мишки, большой плюшевый медведь, плюшевые мишки купить, купить большого медведя
Запятые являются разделителем ключевых фраз. То есть мы изначально указываем поисковому роботу, какие именно словоформы мы хотим использовать.
Пример 2 — ключевые слова через пробел :
Плюшевый мишка большие плюшевые медведи купить огромный плюшевый медведь мягкая игрушка
Мы не разделяем ключевые слова, не указываем конкретные ключевые фразы, позволяя поисковому роботу самостоятельно создавать словоформы.
Какой результат будет более релевантным? Пишите свои предположения в комментариях.
Яндекс и meta keywords
Не все поисковые системы полностью отказались от meta keywords , Яндекс открыто описывает свое отношение к ключевым словам из мета кейводс. И сообщает, что робот Яндекса учитывает содержание тега meta name keywords content в следующей формулировке:
"- может учитываться при определении соответствия страницы поисковым запросам"
Может учитываться означает, что может и не учитываться . Маловероятно, что поисковые системы совсем игнорируют корректно указанные метаданные о странице сайта. И тем более, никто не может гарантировать, что значение мета тега keywords не будет пересмотрено Яндексом (или уже пересмотрено). В любом случае, лучше прописывать ключевые слова в meta keywords, SEO хуже от этого не станет.
Google и meta keywords
Сам Гугл про мета кейвордс заявляет следующее (короткое видео 1:58):
"We don’t use keywords meta-tag in a search-ranking"
Занавес. По крайней мере, честно и однозначно. Верить или не верить Google — дело ваше. Но лучше заполнить слова сразу, чем потом узнать, что тэг meta keywords снова вляет на SEO, и получить тысячи, десятки или сотни тысяч страниц, которым нужно прописать ключевые слова, а шаблоны «палятся» на раз и могут пессимизировать поисковую оптимизацию сайта.
Meta keywords Rambler, Mail.ru, Yahoo, Bing
Важность отношения данных поисковых систем к мета тегу keywords стремится к нулю, тем более, что многие из них используют алгоритмы гигантов рынка, например Яндекса.
Meta keywords в joomla и wordpress
Популярные CMS Joomla и WordPress поддерживают meta name keywords . Что, в свою очередь, подчеркивает востребованность заполнения мета тега для ключевых слова на странице. СЕО не бывает лишним даже если это .
Окончательное решение остается за вами.
Надо сказать, что лишний раз подумать над тем, что такое ключевые слова, и как их лучше использовать на странице, будет полезно для того, чтобы тоньше постигнуть суть SEO оптимизации.
Думайте, анализируйте, комментируйте.
Делайте репосты, подписывайтесь на блог.
И правильно заполняйте мета-теги.
11.1KОдна из самых популярных и необходимых функций на любом сайте – это поиск, реализованный с помощью специальной формы. Этот функционал позволяет посетителям быстро находить на сайте интересующий их контент.
Сегодня мы хотим рассказать, как сделать поиск по сайту с помощью специальной формы, которая будет опрашивать таблицы базы данных и выводить информацию о текущих руководителях на сайте. Вы научитесь создавать таблицы базы данных, которая будет содержать в себе информацию о текущем персонале.
Разрабатывать формы поиска при помощи PHP , а также познакомитесь с SQL (Structured Query Language ) – специальным языком для сбора, записи и модификации информации, содержащейся в базах данных. Перед тем как начать, рекомендуем вам скачать файлы проекта .
Что вам понадобится
- Инструмент для работы с базами данных MySQL .
- Локальный или удаленный сервер с поддержкой PHP .
- Текстовый редактор.
Создаем базу данных
Если вы не совсем уверены, что сможете разобраться с базой данных на вашем хостинге, то свяжитесь с хостером для получения соответствующих инструкций или помощи. После того как база данных будет создана, вам нужно будет подключить ее, создать таблицу и записать в нее необходимые данные.
Самым популярным инструментом для управления MySQL является PHP My Admin , Этого инструмента будет достаточно для нашего сегодняшнего руководства.
Создание таблицы
Наша таблица должна быть создана в следующем формате:
Column Name | Data Type | Length | Null or Not Null | Primary key? | Auto Increment |
ID | INT | 1 | Not Null | Yes | Yes |
FirstName | Varchar | 50 | Not Null | No | No |
LastName | Varchar | 50 | Not Null | No | No |
Varchar | 50 | Not Null | No | No | |
PhoneNumber | Varchar | 15 | Not Null | No | No |
Таблица базы данных состоит из столбцов и строк, как в Excel . Первый столбец позволяет идентифицировать данные по имени. Далее идет колонка Data types (тип данных ), которая указывает нам на тип данных, содержащихся в колонке. В поле Length (Длина ) указывается максимальный объем памяти (хранилища ) для столбца таблицы. Мы используем переменные, которые дают больше гибкости. Другими словами, если длина ФИО меньше 50 символов, то будет занята лишь часть отведенного места.
И среди данных персонала не может быть пустых значений (null, empty ). Первая строка выделена желтым цветом, потому что столбец ID – наш основной ключ. Основной ключ в базе данных гарантирует, что каждая запись будет уникальной. К этой колонке также применен автоинкремент, а это значит, что каждой записи в нашей базе данных будет присваиваться уникальный номер автоматически.
Вносим представителей персонала в таблицу
Как только разберетесь с таблицей, начните заполнять ее данными. 6 записей вполне достаточно, чтобы закрепить в уме процедуру. Ниже предлагаю вам собственный пример:
Column ID | FirstName | LastName | PhoneNumber | |
2 | Ryan | Butler | [email protected] | 417-854-8547 |
3 | Brent | Callahan | [email protected] | 417-854-6587 |
Разработка формы
Чтобы создать форму поиска по сайту через Google , откройте любой подходящий текстовый редактор. Я рекомендую воспользоваться бесплатным PSPad . Вы можете использовать любой текстовый редактор, где предусмотрена подсветка синтаксиса. Это в значительной степени облегчит процесс написания и отладки PHP-кода . Создавая страницу для формы поиска, не забудьте сохранить ее в формате .php , иначе PHP-код не будет обрабатываться должным образом. Как только сохраните документ, скопируйте в него следующую разметку:
Детальный поиск контактов
Вы можете искать по имени или фамилии
Если вы знакомы с языком HTML , то тут вам все должно быть понятно как минимум до открывающего тега form . Внутри этого тега находится важнейший элемент всего кода – атрибут action . В качестве действия нашей формы мы указали название нашего файла, а затем применили к нему строку запроса “go ”.
Проверка на соответствие критерию
Когда пользователь вводит имя или фамилию, а затем нажимает кнопку подтверждения, форма передает данные самой себе и добавляет в конце строку запроса “go ”. На данном этапе мы проверяем наличие строки запроса go . Если результат положительный, выводим результаты поиска.
До вывода запрашиваемых результатов нам нужно перепроверить: (1) была ли подтверждена форма, (2) содержит ли строка запроса значение go, (3) был ли поисковой запрос введен в нижнем или верхнем регистре? Если ни одна из проверок не дает положительного результата (true ), то от нас не требуется выполнять какие-либо действия.
Для начала добавим небольшой блок кода PHP поиск по сайту после закрывающего тега :