ПРОГРАММ: 654 | СТАТЕЙ: 125 | КОДОВ: 3434   

    главная        новости        программы        библиотека        коды        рейтинг       форум   

Афоризм
Богоматерь.ico
 
Поиск


 
Рассылка
| Soft-Ежедневник - обзор программ прямо к Вам на e-mail
 
 
Полезное!
 
7 лучших
  Плиты дорожные, ЖБИ
  Ремонт мониторов
  Все услуги ПриватБанка в Украине
  Business Software Laboratory
  CyberBOARD - доска бесплатных объявлений, открыта для пользователей!
  
  
 
  Библиотека > web - разработка > PHPдобавить статью
Безопасный и удобный поиск

Главное, с чем сталкиваешься при написании скрипта для поиска - то, что все кажется простым, но объем кода быстро нарастает...
 

infocity.kiev.ua
10-05-2004
Версия для печати
печать

Главное, с чем сталкиваешься при написании скрипта для поиска - то, что все кажется простым, но объем кода быстро нарастает.

Обработка строки


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

$search = substr($search, 0, 64);

64 символов пользователю будет достаточно для поиска. Теперь каленым железом выжжем все "ненормальные" символы.

$search = preg_replace("/[^(w)|(x7F-xFF)|(s)]/", " ", $search);

По идее, нельзя давать пользователю возможности искать по слишком коротким словам - кроме всего прочего, это сильно загружает сервер. Итак, разрешим искать только по словам, которые длиннее двух букв (если ограничение больше, надо заменить "{1,2}" на "{1, кол-во символов}").

$good = trim(preg_replace("/s([^s]{1,2})s/", " ", ereg_replace("[ ]%2B", "  "," $search ")));

А после замены плохих слов - надо сжать двойные пробелы (они были сделаны специально для корректного поиска коротких слов).

$good = ereg_eplace("[ ]%2B", " ", $good);

Логика


Допустим, мы хотим предоставить пользователю возможность выбирать логику поиска - искать все слова или только одно из нескольких. Если вы хотите сделать как в Яндексе [2] [1] - два амперсанта означают "И" (слово1&&слово2&&слово3) или как-то еще, то я не советчик. Шаманство со строками на небольшом сайте imho не оправдывает затраченного времени. Поэтому форму для поиска рисуем так:


А в поисковом скрипте лишний раз проверяем, что пользователь ввел:

if ($logic!="AND" && $logic!="OR")
  $logic = "OR";

Как будет использоваться логика — ниже.

Релевантность


Наверное, в том же Яндексе [2] [1] все видели ссылочку "сортировать по релевантности". Это оно и есть. Сортировка результатов по количеству совпадений слов.

Отчасти, кстати, такая сортировка снимает проблему обработки логики поиска. Но с БД MySQL делать такую сортировку очень сложно. Надо сперва выбрать, где есть все слова, потом записи, где разные слова (исключив предыдущие). Если у вас постраничный вывод - то вообще дело труба!

Статистика поиска


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

$query = "SELECT id FROM table WHERE field LIKE "%". str_replace(" ", "%" OR field LIKE "%", $good). "%"";

Для статистики по отдельным словам можно сделать следующее:

$word = explode(" ", $search);
while (list($k, $v) = each($word)) {
  if (strlen($v)>2)
    $stat[]="$v:". mysql_num_rows(mysql_query("SELECT id FROM table WHERE field LIKE "%$v%""));
  else
    $stat[]="$v: <font color=#cc0000>короткое</font>";
  };
$word_stats = "Статистика слов: ". implode("", $stat). "<br>";
unset($stat);

Постраничный вывод результатов


Ну, когда у нас есть макет для поиска и количество строк результата поиска, сделать постраничный поиск - пара пустяков. Проверяем переменную $page (не меньше 0, не больше $results_amount/$rows_in_page).

В запрос, который подсчитывает количество строк (смотри выше), пишем нужные нам поля и поля для сортировки. А потом дописываем

if ($page==0)
  $request .= "LIMIT $rows_in_page";
else
  $request .= "LIMIT ". $page*$rows_in_page. ",". $rows_in_page;

(синтаксис: LIMIT <кол-во строк> либо LIMIT <кол-во строк отступа>, <кол-во строк>)

В результате выполнения подобного запроса мы получим именно те самые строки, которые надо выводить на странице.

Для навигации можно либо рисовать ссылки на следующую и предыдущую страницы, либо, что сложнее, делать панель навигации на несколько страниц.

if ($page>0)
  print ("<a href=search.php?search=". rawurlencode($good). "&page=". ($page-1). ">предыдущая страница</a>");

if ($page<$results_amount/$rows_in_page)
  print ("<a href=search.php?search=". rawurlencode($good). "&page=". ($page%2B1). ">следующая страница</a>");

Подсветка


Чтобы подсвечивать светом или жирным шрифтом искомые слова в тексте, надо сделать всего лишь следующее:


$highlight = "(". str_replace(" ", "|", $good). ")";

Пробелы (а они у нас между словами стоят поодиночке, и нигде двойной пробел не встречается, к тому же с концов строки мы их тоже вырезали) достаточно заменить на вертикальную черту - разделитель вариантов в регулярных выражениях. "Плохие" слова мы не подсвечиваем, потому что в базе их не ищем :).

В коде, который выводит текст пишем:


$row["text"] = ereg_replace($highlight, "<font color=#cc0000>1</font>", $row["text"]);

После написания выпуска я кинулся, было, писать и себе "подсветку". Не тут-то было! У меня в тексте встречаются теги HTML, поэтому пришлось много подумать... Получилась вот такая вещь (строка со словами для подсветки есть):

$text = eregi_replace(">([^<]*)$words", ">1<font color=#cc0000>2</font>3<", $text);

Приходится смотреть, нет в теге ли это слово. Однако тут встает проблема ресурсоемкости такой замены (мой K6-266 над текстом в 5 килобайт думал целых семь секунд). Печально.

Итог


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



Комментарии
Оставить комментарий
страница < | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 |

MazinErrorrorO | 06-12-20 19:23
Anticoagulation ought to be continued for at least three weeks after profitable cardioversion. The ultrasound will be able to decide the size of the defect in addition to identify the organs which are affected. Laparoscopic stripping of endometriomas: a randomized trial on different surgical techniques <a href=https://h2.com/antibiotics/buy-cheap-myambutol-online-no-rx/> bacteria acne discount myambutol 800 mg without prescription</a>.
Anterior choroiditis is usually syphilitic and manifests like disseminated choroiditis but it the nongranulomatous posterior uveitis can also be includes principally the peripheral a part of the generally known as exudative choroiditis as a result of the choroid. Additionally, determining how neurobiological elements contribute to variations in substance misuse and habit between women and men and among racial and ethnic groups is crucial. Oxidative mechanisms of biological exercise of low-depth radiofrequency radiation <a href=https://h2.com/antibiotics/purchase-floxin-online-in-usa/> best antibiotics for sinus infection mayo clinic buy floxin 400mg fast delivery</a>. Consideration is ing of this association and allow more definitive hampered by the relative recency of widespread conclusions. The 438 complications of chemotherapy differ with the regimen пїЅпїЅпїЅ et al: Molecular therapy in head and neck oncology. Cerebrovascular accident selected by the General Principle, is considered a general time period and cerebral thrombosis is most po


FadiAbilt | 18-11-20 03:55
Papular, erythematosus, and purpuric lesions could happen on fingertips, elbows, toes, and extensor surfaces of forearms or lateral sides of hands and may progress to necrosis. The practice is rooted in cultural understandings of gender, sexuality, marriage and household. The ischaemic stroke has stabilized, spontaneously invariably, final lower than one hour symptoms yellow fever <a href=https://scottcountyrepublicans.org/conference/buy-cyclophosphamide-no-rx/>discount cyclophosphamide 50 mg without a prescription</a>.
Dopamine depletion and depigmentation of the substantia nigra is characteristic of Parkinson disease. It is recognized that there are rare systemic disorders, similar to Papillon Lefevre Syndrome, that usually outcome in the early presentation of severe periodontitis. Further, we discovered 5 hours publish fertilization (hpf) by way of the larval stage (ninety six hpf) to 0 prostate cancer freezing treatment <a href=https://scottcountyrepublicans.org/conference/buy-proscar-online-in-usa/>cheap proscar 5 mg on-line</a>. Since they're the medical presentation of signs including a significant threat of altered alertness, agitation and hyperactivity, altered sleep-wake cycle and psychosis. Experience in genetic counselling and training in laboratory procedures for the prognosis of genetic ninety five issues are likewise included. Int J Impot Res 1999;11(1):29пїЅ Phosphodiesterase Type 5 Inhibitors Cure Erectile 32 erectile dysfunction caused by vasectomy <a href


JavierVoseBrego | 03-11-20 22:15
Searing:the physique half is totally burned virtually beyond the purpose of recognition. Examples of this kind of reaction include acetaminIn situations where pores and skin test outcomes can't be interpreted ophen-induced hepatic toxicity, sedation from antihistaproperly (ie, generalized eczema, dermatographism, or lack mines, and interference of theophylline metabolism by of response to the optimistic histamine management) some in vitro erythromycin. Va ccine Spelm a n uttery a ley A eta l uidelines o rthe preventio no f sepsisina splenica ndhypo splenicpa tientsInternM ed J W einerM L a ndm a nnR ePa redesL, eta l: Vesicula tederythro cytesa sa determ ina tio no f splenicreticulo endo thelia l unctio ninpedia tricpa tientswith Ho dgkinпїЅ sdisea se <a href=https://dev.org.es/exploration/buy-cozaar/index.html> diabetes insipidus yahoo group buy cozaar in united states online</a>.
Older babies seem to be able to recognise (Sydney metropolitan area) or the distinction between the dummy and the breast. His physical examination is totally normal aside from a purulent discharge that may be expressed from his penis. Immunotherapy with ragweedmonoclonal antibody agent, Omalizumab, to establish appropriate toll-like receptor agonist vaccine for allergic rhinitis <a href=https://dev.org.es/exploration/purchase-cialis-soft-no-rx/index.html> impotence beavis and butthead purchase cheap cialis soft</a>. Two subously and has a predictable e?ect within one hundred twenty minutes stance


Ur-Goshcuccari | 03-11-20 11:02
A healthy, premature, 2100-g male toddler was delivered 48 hours after thrombolysis. Despite a start difficult by fetal distress requiring assisted forceps delivery, the apparently healthy female infant had no evidence of sedation or withdrawal and remained properly throughout breastfeeding. Little curiosity or pleasure September 2013 пїЅ Presentations (in addition to obvious unhappiness) in doing issues <a href=https://dev.org.es/journal/order-indinavir/index.html> medicine naproxen buy cheap indinavir 400 mg on-line</a>.
Iervolino and colleagues (2002), for example, used two genetically-sensitive knowledge units to look at the environmental and genetic influences on adolescent peer group socialization. Semidiagrammatic frontal sections of feminine melanops (C), and Macroglossus minimus (D). Fusion was an extended surgery with extra related Matsunaga et al4 introduced outcomes from a retrospective study blood loss and longer hospital stay <a href=https://dev.org.es/journal/buy-cheap-atacand-online/index.html> symptoms of hiv infection after 3 months buy genuine atacand</a>. We concluded that peritoneal lavage has an anti-inflammatory impact in acute pancreatitis. Acute Pulmonary embolism Defnition: It is an acute situation resulting from clot embolism into the pulmonary arterial circulation, resulting in reduction of blood fowing in the pulmonary arteries Classifcation Classifcation of Pulmonary embolism пїЅ Small or Moderate: Normal hemodynamics and normal proper ventricu


SanfordNemnize | 30-10-20 18:08
Mosaicism can be identified by sending a pattern of the affected personпїЅs pores and skin, obtained via a skin biopsy, to a certifed scientific cytogenetics laboratory, which may perform the chromosome 31 Fanconi Anemia: Guidelines for Diagnosis and Management breakage test on fbroblast cells present in the skin pattern. A thorough historical past can be essential to determine the presence of co-occurring psychiatric situations or physical disorders that have to be addressed in therapy planning (American Psychiatric Association 2016a; Firth et al. According to the American Heart Association the syndrome Ois defned by a combination of conditions that lead to a higher danger for coronary artery disease <a href=http://meak.org/science/Kelly-C-Rogers/order-online-levitra-professional-no-rx/> erectile dysfunction treatment vacuum pump purchase levitra professional 20 mg mastercard</a>.
N ormal estrogen bers that provide the vestibular epithelium could turn out to be ranges keep a thick, protective squamous epithelium highly sensitized, causing neurons within the dorsal horn of that accommodates glycogen. The roles of existing care supply organizations, such as community well being facilities, are also being expanded to meet the demands of built-in look after substance use dysfunction prevention, treatment, and recovery. These research permit for targeted genetic testing in threatening dysfunction of gluconeogenesis, presents throughout the select instances (70) <a href=http://m


Jackkakly | 25-10-20 23:26
The probabilities kids have in training is a vital concept in Ireland however the lack of enough educational companies for children who've chronic illnesses like Cystic Fibrosis needs to be addressed. Maintenance of parasites in laboratory both in vivo in animals or by in-vitro cultures 2. However, about half of these tumours discovered within the ampulla are thought of to be of low grade malignancy <a href=https://globalcad.org/berkeley/deryk-van-brunt/buy-cheap-ashwagandha-no-rx/> anxiety symptoms electric shock sensation feelings discount 60 caps ashwagandha amex</a>.
One study described that seizures which develop Correct willpower of the epilepsy syndrome and appropriwithin the primary year after injury usually tend to remit with ate selection of medical and surgical management is crucial to medicine than those that seem later (86). During this time, you will the monitoring tools allows the anaesthetist and remain in bed. Chronic System ic Toxicity There is a few evidence from chronic experimental animal studies that ingest- ing excessive doses of picloram affects the liver <a href=https://globalcad.org/berkeley/deryk-van-brunt/purchase-albenza-no-rx/> symptoms zoloft withdrawal purchase albenza online pills</a>. Children Oral vials: Each a hundred ml contains: Ranunculus bulbosus 4X, 10X, 15X, 30X, 200X, to 6 years: half the grownup dosage. Neck stifness, photophobia and focal neurology eye actions are uncommon in cerebral malaria. The infarcts comply with excessive-d


Lucabor | 06-10-20 21:33
Is the system designed to accommodate the amount of knowledge traffic you possibly can expect on a routine foundation?. In populations of breeding animals mating of parents is usually not advert random and oldsters are selected for breeding objective traits. Role of serum endotoxin and antiendotoxin core antibody levels in predicting the event of a number of organ failure in acute pancreatitis <a href=https://www.sironabiochem.com/medications/catalog13/example3/> erectile dysfunction under 25 9pc vpxl amex</a>.
A malignant tumor, nonetheless, will, regardless whether it's positioned dorsal or ventral from the matrix, lead to a partial destruction of the matrix inflicting a longitudinal defect or fssure of the nail plate (Figure 15. Last replace: July 2019 Page 197 of 206 Guideline for Isolation Precautions: Preventing Transmission of Infectious Agents in Healthcare Settings (2007) 972. The Trickster God, the God of Deception Huehuecoyotl, Old Coyote, the Trickster, god of deception, this god is a prankster who loves to drag pranks on individuals and on the gods <a href=https://www.sironabiochem.com/medications/catalog13/example2/> erectile dysfunction daily medication purchase silagra with a visa</a>. Many extra alternatives for progress via persevering with and new toxicologic, mecha- nistic, and epidemiologic research exist. Hepatic arterial infusion of floxuridine in patients with liver metastases from colorectal carcinoma: long run outcomes of a prospective randomised t


Tylerkix | 06-10-20 20:22
HoffmannпїЅLa Roche and Chugai Pharmaceu- the EmiPref survey as a result of some sites were un- tical. Plan the key steps and know the potential pitfalls in performing gastric emptying b. As part of the midcourse evaluate of the physical after the group instituted an academic and rec- exercise and health objectives ofHealthy People 2000, reational assist program for youngsters (National the council introduced a synopsis of ongoing grassroots Park Service 1994) <a href=https://www.sironabiochem.com/medications/catalog27/example10/> allergy tcm treatment order prednisolone 10 mg with mastercard</a>.
Patients receiving kidney grafts must be correctly hydrated to permit instant kidney graft function. After having cited critically some opinions on the pos- From these ideas Garrod drew extra far-reaching sible causes of alkaptonuria, Garrod proceeded: conclusions, which are sometimes ignored. See photomicrograph below of spinal twine with reactive / inflammatory focus containing pink pigment <a href=https://www.sironabiochem.com/medications/catalog27/example4/> herbs to lower cholesterol generic himplasia 30caps online</a>. Importance and management Contrary to what was predicted from in vitro research using tangeretin, a single dose of tangerine juice didn't appear to change the pharmacokinetics of midazolam. The ischaemic stroke has stabilized, spontaneously invariably, final lower than one hour. She has published broadly on environmental exposures, including metals, pesticides


HenryRap | 29-09-20 16:08
&#1057;&#1077;&#1075;&#1086;&#1076;&#1085;&#1103; &#1076;&#1072;&#1078;&#1077; &#1088;&#1077;&#1073;&#1077;&#1085;&#1086;&#1082; &#1079;&#1085;&#1072;&#1077;&#1090;, &#1082;&#1072;&#1082; &#1079;&#1072;&#1088;&#1072;&#1073;&#1086;&#1090;&#1072;&#1090;&#1100; 100 &#1076;&#1086;&#1083;&#1083;&#1072;&#1088;&#1086;&#1074;.
&#1057;&#1089;&#1099;&#1083;&#1082;&#1072; - - http://www.google.com/url?q=%68%74%74%70%73%3A%2F%2F%68%64%72%65%64%74%75%62%65%33%2e%6d%6f%62%69%2F%62%74%73%6d%61%72%74%23%51%41%78%77%4d%53%54%54%4e%43%44%71%6f%64%6f%65%4d&sa=D&sntz=1&usg=AFQjCNHvmmVTlT7LL-o4lqaYfEFHmsHo1w


JOKER Board Commercial 3 | 13-12-09 23:57
Joker Board Commercial 3 за 20 баксов под ключ! ICQ:183917
Скрипт доски объявлений JOKER Board Commercial Version 3.
Надежный скрипт на котором построены уже сотни досок!
JOKER Board Commercial Version 3 - это надежность
JOKER Board Commercial Version 3 - простота настройки
JOKER Board Commercial Version 3 - простота использования
JOKER Board Commercial Version 3 - проверен на сотнях сайтов

Продаю свою лицензию, цена 20$
Подробности в ICQ 183917

Joker Board Commercial 3 за 20 баксов под ключ! ICQ:183917

=====>
joker board joker board joker board commercial joker board скачать joker board commercial version joker index php phpsessid board скачать joker board commercial joker board скачать joker board joker board commercial joker board скрипт joker board commercial version joker board null joker board ver скачать скрипт joker board joker board commercial скачать joker board nulled joker board скачать бесплатно joker board ver скачать joker board commercial version joker board v продам joker board joker board v сайт joker board joker board commercial full модуль вывода joker board joker board commercial продаю скачать скрипт joker board joker board dle

Имя:
E-mail:
Сообщение:


Число=
укажите сумму чисел на картинке

   очистить

популярные статьи по теменовые статьи
Создание видео из фотографий в программе "ФотоШОУ"
Разное / Обработка фото и видео
Больница для компьютера
железо / Система
Чем так популярны социальные сети?
Разное / разное
Синхронизация данных с сотового телефона на ПК
железо / Мобильные устройства
Куплю хостинг
web - разработка / Хостинг

Опрос
На что Вы обращаете внимание в первую очередь при покупке товара в интернет-магазине?  
 
Комментарии и оценку пользователей
Наличие нескольких фотографий
Подробное и качественное описание
Условия доставки
Возможность покупки в кредит
 
Самое свежее  
 ПРОГРАММЫ

ICQ 8.0.5990
ICQ 8.0.5990

Mozilla Firefox 18.0.2
Mozilla Firefox 18.0.2

ArtMoney 7.40.4
ArtMoney 7.40.4

 НОВОСТИ

Хакерская атака на Google из Китая
Хакерская атака на Google из Китая

Мы победили! Олимпиада 2014 пройдет в Сочи
Мы победили! Олимпиада 2014 пройдет в Сочи

 БИБЛИОТЕКА

Создание видео из фотографий в программе "ФотоШОУ"
Создание видео из фотографий в программе "ФотоШОУ"

Больница для компьютера

 
Рекомендую!



Copyright © 2004-2024 MostInfo.net  | связь с админом
При использовании материалов сайта ссылка на MostInfo обязательна.