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

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

Афоризм
Электpоника - это наука о хpеновых контактах.
 
Поиск


 
Рассылка
| Soft-Ежедневник - обзор программ прямо к Вам на e-mail
 
 
Полезное!
 
7 лучших
  Тематический портал продажи оборудования для уличной торговли и другого с доставкой
  Немецкий инструмент Knipex на интернет-сайт knipex.pro
  Перегрузка сыпучих грузов
  знакомства
  Бесплатная доска объявлений
  
  
 
  Библиотека > 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 тысяч раз лазил в базу) в) увидеть сообщение об ошибке в результате попадания в строку спецсимволов языка запросов. Во-вторых, некоторое удобство для пользователя - постраничный вывод и подсветка.



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

Gembakhirty | 30-01-22 08:20
With therapeutic use, the overall variable half-lives, volumes of distribution, and protein binding. Severe (decompensated) anaemia An grownup with properly-compensated anaemia could have few or no signs or indicators. Navigational Note: - Uterine obstruction Asymptomatic; medical or Symptomatic; elective Severe signs; invasive - - diagnostic observations only; intervention indicated intervention indicated intervention not indicated Definition: A disorder characterised by blockage of the uterine outlet medicine quotes doctor <a href=http://institutoitm.edu.ar/explore/purchase-lamotrigine-no-rx/>discount lamotrigine 50mg</a>.
Infections involving a single serotype could vary broadly of their presentation; a number of serotypes can produce the same medical syndrome. The upper central and lateral incisors present extensive decay and are barely free. The nurse replies that the fetus is most vulnerable to teratogens from the third to eighth week after conception, which is commonly before ladies know they're pregnant virus buster <a href=http://institutoitm.edu.ar/explore/purchase-cheap-terramycin-online/>generic terramycin 250mg with visa</a>. The truth is that a gender evaluation is a vital component of all public insurance policies which are crucial to the safeguarding and enhancement of womenпїЅs well being. Tires: Check the air in your tires earlier than leaving; consider packing a conveyable pump. Admit For Acute exacerbation Bed relaxation (might have to splint the affecte


ArokkhRabbala | 20-01-22 04:49
Selenium sulfide is a complementary drug for use in rare problems or in exceptional circumstances. It is probably going that the thyroid phenotype in Frs2a mutants role for cranial neural crest in thyroid improvement (Bockman and depends, at least partly, on impaired regulation of thyroid Kirby, 1984), and more modern findings point out that subpopulations growth by Tbx1-Fgf8. These fndings assist the data profoundly suppressed within the hypoparathyroid topics cholesterol content chart <a href=https://thelizlogelinfoundation.org/faculty/purchase-online-crestor-cheap/>generic crestor 5 mg</a>.
Based upon trials and mishap records, this could show to be enough time for all of the occupants to evacuate the helicopter before it submerges. However, a stronger advice was not attainable as the diagnostic accuracy of the tests isn't known. Panic-targeted psycho- der, choosing a medication for a specific affected person mainly dynamic psychotherapy makes use of the final rules of entails issues of side effects (including any appli- psychodynamic psychotherapy, with particular focus on the cable warnings from the U erectile dysfunction what age <a href=https://thelizlogelinfoundation.org/faculty/buy-online-super-avana/>buy online super avana</a>. Educational analysis practices of pros serving students who are deaf or onerous of hearing: An initial investigation. Therefore, in a balanced translocation, the wild-type X chromosome is all the time inactivated, leaving the translocation


Hengleymet | 06-01-22 17:40
Rabbits: Species Route Dose #Animals/ Duration Findings mg/kg/da dose stage y Maternal toxicity research in rabbits by the oral route (95003/95004) New Oral 50 7 females Gestation Pregnant females and fetuses had been exposed to the drug. Wheal and flare occur on the site of intradermal by mediating cell-to-cell interplay. This might be considered if all other special care items of the hospital are at capacity symptoms juvenile diabetes <a href=https://db.berkeley.edu/openfiles/nevirapine/>order cheapest nevirapine and nevirapine</a>.
Disulfuram Flushing (Antabuse) and, to a lesser extent, chlorpropamide this transient vasodilatation of the face might spread inhibit aldehyde dehydrogenase so that some indito the neck, higher chest and, extra not often, other parts viduals taking these medicine may ush. Brief communication: Better ways to question sufferers about opposed medical occasions: a randomized, controlled trial. The Authorised Health Professional considers a variety of problems that will trigger blackouts medications not to take with blood pressure meds <a href=https://db.berkeley.edu/openfiles/boniva/>buy boniva without a prescription</a>. Antiepileptic Treatment of Posttraumatic Stress the administration of frequent baldness. Overdose additionally produces the primary treatment, neostigmine + atropine weakness by inflicting persistent depolarization of forestall respiratory paralysis. Further screening of one hundred wholesome Maltese control people resulted in th


Gamalbuggext | 04-01-22 02:13
These restrictions are specifc to every dysfunction Nutrition Interventions for Children With Special Health Care Needs 237 Chapter 21 - Nutrition Interventions for Metabolic Disorders and include, for instance, the restriction of specifc amino acids or complete protein, fatty acids, easy sugars, or complete carbohydrate (1,2). Distortion product otoacoustic emissions in youngsters at college entry: a comparison with pure-tone screening and tympanometry outcomes. These outcomes are associated to the recognized pharmacological facts concerning mephedrone, its possible interactions with alcohol and other psychoactive medicine, and advised scientific interventions and treatment(s) medicine 20th century <a href=https://db.berkeley.edu/openfiles/zupar/>best order zupar</a>.
Cadet Enrollment/Ethnic Data Report/School-Unit Information Report (including Academic Credit by School). This seems to be the major concern of tonsils to staff children's bodies recognize, destroy, and broaden vaccination to proverbial environmental pathogens so that they desire be protected in their later lives. Some of the species presently thought of valid are: a dwarf form of Diphyllobothrium, described as D blood pressure chart age 40 <a href=https://db.berkeley.edu/openfiles/hytrin/>quality 1mg hytrin</a>. Women planning pregnancy and who're drug customers, ought to be adviced about quitting в€љ this behavior and be provided with dishabituation measures. There could be a neurobiological correlation to


VibaldBrigo | 01-01-22 23:17
Eggs remain period infective for as much as 2 weeks Exclusion Do not exclude Treatment Treatment out there � refer to doctor Contacts Do not exclude Immunisation None out there 34 Communicable disease pointers 2017 Edition Pneumococcal disease (Streptococcus pneumoniae) P Notifable � discuss together with your native public health unit workers. This usually entails mixtures of ultrasound and cardiotocography, aiming for planned early supply at 38 weeks’ gestation. However, the shown that Cougar populations are actually in decline, and reviews that a rise in Department can also be mandated to offer leisure alternatives related cougar looking on a fragile population has not solved cougar-human conflicts, I with wildlife, and cougar looking is one sort of activity underneath this mandate, as respectfully impress up on you to actively educate the general public about cougar habits, long as searching ranges are in keeping with long-term, viable cougar populations autoimmune gastritis definition <a href=https://www.cascanueces.edu.co/scientific/buy-online-macrobid-cheap/>order macrobid 50mg amex</a>.
Nicotine ought to be placed on those who wish to market and sell use may result in using other tobacco such tobacco products, somewhat than the general public health comor nicotine-containing products. The affected person subsequently underwent revision instrumentation from T10 to the pelvis with use of a 4-rod construct (H,I). The depth of this preparation may be standardized


Murakhance | 01-01-22 07:50
Pigmented purpuric dermatoses Synonyms: Idiopathic pigmentary purpura, Purpura simplex, Chronic capillaritis, Purpura pigmentosa chronica Clinical features, Classification Pigmented purpuric dermatoses happen most incessantly within the decrease extremities of center-aged men. Resection of an asymptomatic major colon most cancers in Management of Locoregional Recurrence patients with incurable metastatic most cancers is mostly 1. Phyllodes tumor, malignant A thirteen-yr-old male presents with bilateral enlargement of his breasts treatment 9mm kidney stones <a href=http://institutions.northsouth.edu/course/mildronate/>order mildronate 250 mg with visa</a>.
Tetracycline and niacinamide: remedy alternate options in ocular cicatricial pemphigoid. Diabetes Care 17:1007–1014, hospital using guideline-directed or- aesthesia 39:629–637, 1984 1994 ders. Light, if part of name; the sunshine: Boston K Bufalo South Pier Light 2; however light No infantile spasms 7 month old <a href=http://institutions.northsouth.edu/course/zanaflex/>order zanaflex online now</a>. A fetus born alive with abnormalities incompatible with life ought to be managed to maintain comfort and dignity during terminal care (part eight). The extrapolation performance of every method was microbiomes, mucosal infammation, and screening of colorectal care prod- evaluated using 20-fold cross validation. If the delusions persist, the diagnosis ought to be changed to persistent delusional disorder (F22 gastritis and


VarekUnsesurce | 07-12-21 10:56
The last chapter is a compendium of lots of of systemic ailments and chromosomal abnormalities that affect the attention. A Multi-modal Convolutional Neural forty two Network Framework for the Prediction of Alzheimer’s Disease. Focal seizures: Focal epileptic seizures are conceptualized as originating inside networks restricted to at least one hemisphere birth control pills emergency contraception <a href=https://trustuniversity.edu.bd/biomedical/order-levonorgestrel-bp/>levonorgestrel 0.18mg for sale</a>.
A Short Text- the event of the current set of descriptions and guide of Medicine, fifth ed. Gnathostomiasis and sparganosis could produce larva migrans the place the lesions are deeper, subcutaneous or within the muscular tissues. You may then get hold of quick entry to the ProView database by way of the Internet to finish and submit your application <a href=https://trustuniversity.edu.bd/biomedical/buy-arzomicin-no-rx/> virus 7th grade science order 500 mg arzomicin mastercard</a>. Induration size on the volar forearm was measured in millimetres (mm) utilizing a flexible studying ruler. A 26-year-old woman is delivered to the emergency department because of an eight-hour historical past of extreme again and belly ache and gentle but persistent vaginal bleeding. The anxiousness, despair, and, more not often, hallucinations frst is an involuntary contraction of the forearm muscular tissues and psychotic episodes (C) (103) anxiety 1-10 rating scale <a href=https://trustun


GioresNeibrobia | 06-12-21 19:52
Mobilizing and strengthening financial, and human and institutional capacity throughout all sectors, particularly in well being and training. There is an pressing need for head-to-head comparisons of different biologics in sufferers eligible for a couple of biologic. There is variable degree of fattening of the mucosa, notably of the higher jejunum, and to some extent of the duodenum and ileum arrhythmia nos <a href=https://trustuniversity.edu.bd/biomedical/purchase-cheap-coumadin/>purchase 1mg coumadin with visa</a>.
However, logic dictates that in these circumstances dismanifestations, psychogenic signs characterize a challenge capacity should be filed and justified on the basis of a psychiatric each in diagnosis and in administration. The Impact of Lesion In-Painting and Registration Methods on Voxel-Based Morphometry in Detecting Regional Cerebral Gray Matter Atrophy in Multiple Sclerosis. Care supplier: Encompasses both healthcare professionals and other professionals who do not provide medical services, corresponding to counselors or providers of supportive companies antibiotic for uti gram negative rods <a href=https://trustuniversity.edu.bd/biomedical/order-online-augmentin-cheap-no-rx/>order discount augmentin on-line</a>. These modifications include a diet low in saturated fats (<7% of whole daily energy) and low in cholesterol (<200 mg/d), in addition to train, which can help to decrease cholesterol. Managing asymptomatic 28E Can J Cardiol Vol 20 Suppl E October


DaroNitteeWep | 06-12-21 19:22
Patients with mild disease frequently current in adolescence or adulthood with hemarthroses or extended bleeding after surgery or trauma. Online there may be uncertainty over using preventive medication or eighty two,437,552 threat-assessment calculators could also be used regardless of whether when usual preventive choices are tough to use. This is solely the share of the whole population and between urchin populations which are very body weight of the urchin that is made up by the goclose to one another antibiotic 93 7158 <a href=https://trustuniversity.edu.bd/biomedical/purchase-cheap-roxithromycin/>order genuine roxithromycin</a>.
A poor protein intake generally results in hair loss, slowed development and depigmentation (graying). Lasers, whereas a signifcant assist in certain operations, are costly and usually are not necessarily higher or more practical than other surgical techniques or instruments used during operative laparoscopy. Patients should be encouraged to work with their provider and staff to share decision making concerning glycemic targets, therapies, and objectives of therapy erectile dysfunction following radical prostatectomy <a href=https://trustuniversity.edu.bd/biomedical/order-cialis-professional-online-no-rx/>discount cialis professional 40 mg free shipping</a>. ZygomatIc arch prognosis the two fractured fragments of zygomatic arch fracture have three fracture traces. Ebstein anomaly: Congenital coronary heart defect characterized by downward disp


Danapepe | 02-12-21 22:36
Helminths trigger direct losses due to deaths and oblique losses due to lowered productiveness through decreased feed intake and liveweight features and, decreased quality of skins, wool or mohair. From Poitout and Robertson45 with permission subsequently resulted in greater insulin secretion. Evidence limitations included the heterogeneity of remedy protocol (numbers of periods, energy intensities, focus sizes differed amongst studies) and most research have been of low high quality infections of the eye <a href=https://titumircollege.gov.bd/bulletin/order-mectizan-online-no-rx/>purchase 3 mg mectizan</a>. For the movement to be precise and to be “over-promised” are not solely the potential out- easy, all of the nerve cells within the “grabbing-the-pen comes of both embryonic and adult stem cell network” should perform properly, together with cells that analysis, but additionally the time scales which are involved. From ClinVar Gene-Phenotype Associations genes associated with the Peripheral demyelinating neuropathy, central dysmyelination, Waardenburg syndrome, and Hirschsprung illness phenotype from the curated ClinVar Gene-Phenotype Associations dataset.
Measure the catheter and compare it with the size listed in Measurement and inspection ensures entire catheter was removed. Increase in heart price is probably the most dependable indicator of effective resuscitative efforts eight. In the multicentric retrospective examine of the French Association of Surgery, 1

Имя:
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 обязательна.