По идее, нельзя давать пользователю возможности искать по слишком коротким словам - кроме всего прочего, это сильно загружает сервер. Итак, разрешим искать только по словам, которые длиннее двух букв (если ограничение больше, надо заменить "{1,2}" на "{1, кол-во символов}").
А после замены плохих слов - надо сжать двойные пробелы (они были сделаны специально для корректного поиска коротких слов).
$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).
В запрос, который подсчитывает количество строк (смотри выше), пишем нужные нам поля и поля для сортировки. А потом дописываем
Пробелы (а они у нас между словами стоят поодиночке, и нигде двойной пробел не встречается, к тому же с концов строки мы их тоже вырезали) достаточно заменить на вертикальную черту - разделитель вариантов в регулярных выражениях. "Плохие" слова мы не подсвечиваем, потому что в базе их не ищем :).
После написания выпуска я кинулся, было, писать и себе "подсветку". Не тут-то было! У меня в тексте встречаются теги HTML, поэтому пришлось много подумать... Получилась вот такая вещь (строка со словами для подсветки есть):
Приходится смотреть, нет в теге ли это слово. Однако тут встает проблема ресурсоемкости такой замены (мой K6-266 над текстом в 5 килобайт думал целых семь секунд). Печально.
Итог
Применяя такие приемы, можно, во-первых, ограничить свободу действий пользователя и не дать ему а) узнать программную структуру сайта б) вызвать перегрузку сервера (например, отправив мегабайт текста, состоящего из слов длиной в три буквы (фраза получилась двусмысленная, но переписывать не буду :), чтобы скрипт 250 тысяч раз лазил в базу) в) увидеть сообщение об ошибке в результате попадания в строку спецсимволов языка запросов. Во-вторых, некоторое удобство для пользователя - постраничный вывод и подсветка.
GanckaVob | 07-09-21 18:31 Current insurance policies usually are not very effective in selling longer length of breastfeeding. The Heritability of Experience The failure of behavioral geneticists to ?nd a lot evidence of shared environ- mental in?uences seems inconsistent with an extensive empirical literature in developmental psychology demonstrating a powerful association between rearing circumstances and psychological outcomes. Psychotic disorders with or with out mediwith management conditions for sufferers with psychoses have cations impotence and smoking <a href=https://halalfoundation.org/programs/standard26/presentation5/>buy 100 mg kamagra polo</a>.
Causes embody renal tubulo-interstitial area is affected, and renal dysпїЅ IgA nephropathy (Berger illness), peri-infectious or submitпїЅ operate is marked (see Table 22-three). Risk components for serious prescription opioid-related toxicity or overdose amongst Veterans Health Administration patients. There is a few evidence that methylphenidate has brief-term advantages in reducing hyperactive and oppositional behaviour in the course of the preschool interval women's health center murfreesboro tn <a href=https://halalfoundation.org/programs/standard26/presentation7/>buy 100 mg gyne-lotrimin overnight delivery</a>. Use intraoral periapical radiography to supplement the preliminary data from panoramic radiography. Ceftriaxone could be an inexpensive choice for a non-neutropenic, well-showing affected person with fever and a central venous gadget
RockoCRUICKY | 01-09-21 18:18 Maternal laboratory checks have been vital for blood kind O constructive and adverse for group B Streptococcus. Antimicrobial lessons for which resistance has turn out to be a serious problem embody the lactams, the glycopeptides, and the uoroquinolones. Confrmed by: a number of comedones; open (blackhead spots) or closed (whitehead spots), in addition to papules and pustules, cysts, and scarring, depending on severity <a href=https://cfcpac.org/nonprofit/purchase-online-levitra-oral-jelly-no-rx/> erectile dysfunction treatment definition buy discount levitra oral jelly on line</a>.
Bottle fed infants: Prepare as above and use the table under to calculate the quantity to be added to a feed: Volume of milk (ml) Gaviscon answer to be added (ml) one hundred 5. The placenta shows much intervillous brin and immunoglobulin deposits of principally IgG and IgM. This schedule refined by discussion with members of the professional reference group, coated areas the kind of programme supplied to students, elements of the course that covered prescribing, interdisciplinary educating, assessments and feedback <a href=https://cfcpac.org/nonprofit/order-cheap-eriacta/> 498a impotence order eriacta with amex</a>. Determinants of Technical Effciency Differentials amongst Smalland Medium-Scale Farmers in Uganda: A Case of Tobacco Growers, by Marios Obwona, Research Paper 152. Following Sebastian Shaw's demise at the hands of Lehnsherr, she (together with the rest of the Hellfire Club mutants)
FlintWresiamma | 30-08-21 15:06 Changes gloves when contaminated, glove integrity is compromised, or when otherwise essential. On the flanks of the main part, medial to the rectus abdominis, the abdominal partition is composed of three layers. The drug given for self-therapy ought to be totally different from that used for prophylaxis <a href=https://restorecal.org/experience/buy-minocin-online-in-usa/> antibiotic resistant sinus infection buy minocin 50 mg</a>.
There is little indication, nevertheless, that noticed enhancements are as a result of auditory options of those packages. Evangelista A, Falk V, Frank H, Gaemperli O, Grabenwoger M, Haverich A, Iung Steinbeck G, Wegscheider K, Meinertz T. Performance & Life Science Chemicals | Key figures million 2009 2008 in % Total revenues 1,202 1,249 –three <a href=https://restorecal.org/experience/order-online-imitrex-no-rx/> muscle relaxant drugs z order imitrex 25 mg on line</a>. Annunziata, 12 50122 Florence, Italy Tel: (+39) 055 20 330 Fax: (+39) 055 2033 220 florence@unicef. The scapula are retracted and elbows pulled again and held for a sluggish depend of three. Permanent cells these cells lose their capability to proliferate across the time of birth <a href=https://restorecal.org/experience/buy-cheap-vardenafil/> erectile dysfunction treatment drugs buy cheapest vardenafil and vardenafil</a>.
Prior cytoreductive remedy that makes anaesthesia secure may be needed prior to any diagnostic try. The fnal databoth sexes, and restricted evidence of carc
ZubenTwire | 26-08-21 02:16 Dose counting and the usage of pressurized metereddose inhalers: working on empty. Use code 95 when a constructive lymph node is aspirated and there are no surgically resected lymph nodes. Supporters of the Viral Hepatitis Action Plan are dedicated to ensuring that new instances of viral hepatitis are prevented and that persons who are already infected are tested; informed about their an infection; and supplied with excessive-quality counseling, care, and remedy <a href=https://gbgroupinc.com/wp-content/specialization/order-online-thyroxine/> medications online discount generic thyroxine uk</a>.
A typical Marfan Weill Marchesani syndrome continues to be un syndrome patient is tall, lean, with excessive sure. Drugs, chemicals and bodily agents which induce aplasia include hydrolases, elastase, myeloperoxidase, cathepsin-G, of the bone marrow trigger neutropenia. Evidence desk forblinded lactose intolerance treatmentstudies:Q uestion4 (continued) A uth or,Y ear, SubjectSelection, Study Design, Treatm ent- O utcom e DataSource,M eth ods Treatm ent-A ctive, Study Subject C ontrol, assessm ent/ Q uality ofth e to M easure O utcom es, A dh erence Sponsorsh ip, C h aracteristics A dh erence R esults and Study Inclusion/Exclusion Evaluations C ountry,L ength of Evaluations C onclusions C riteria F ollowup symptom buteasily tolerated);2=reasonable; three=extreme;and four=very extreme <a href=https://gbgroupinc.com/wp-content/specialization/buy-prinivil-online/> blood pressure chart
HamidNox | 25-08-21 07:37 Items that may be coated (see Schedule of Benefits for standards, restrictions, and limitations) embrace: examinations, x-rays, fillings, restorations, root canals (anterior teeth), extractions, some surgical procedures, general anesthesia, sedation, and dentures. The supermarket had closed, and John Cotton was within the car parking zone, walking toward his automobile, when a stranger approached him, carrying a bundle. Hauser Section B Epileptogenesis, Genetics, and Epilepsy Substrates Chapter 3 Experimental Models of Seizures and Mechanisms of Epileptogenesis 20 T <a href=https://gbgroupinc.com/wp-content/specialization/order-desloratadine-online-no-rx/> allergy shots everett clinic buy discount desloratadine line</a>.
Hematopoietic stem cell transplantation usually makes use of stem cells from the bone marrow or umbilical twine blood of a matched donor. Few of these scales are well Many ventilated pediatric sufferers require sedation and a few validated, particularly in populations of acutely sick children with analgesia while intubated. Clinical concerns and antagonistic events/side effects are not supposed to be inclusive of all data, however somewhat to spotlight a number of the key points <a href=https://gbgroupinc.com/wp-content/specialization/purchase-eurax/> skin care treatments 20 gm eurax</a>. Normally as a result of failure of the preliminary remedy, particularly with breastconserving therapies. The stool Kato-Katz check is widely used; performпїЅ praziquantel
MiltonGaw | 25-08-21 00:50 This is a unique place for fashionable women's clothing and accessories.
We offer our clients women's clothing, jewelry, cosmetics and health products, shoes, bags and much more.
https://fas.st/aLmjv
CarlosVof | 19-08-21 17:17 Encourage coughing, deep-respiration workouts, and frequent Promotes lung growth, mobilization, and drainage of position adjustments. The challenge well being activities, including advocatng fuoridation of comВ for dentist, therefore, is to look beyond the person dental munity water supplies, partcipating at school and commuВ ofce and make a broad evaluation of their community's nity well being promotion actions, advocating for physicians needs while assessing their very own position in enhancing the oral to be reimbursed fo r the application of fuoride varish for health of the complete community. A lower during which of the next more than likely promotes edema formation on this affected person? <a href=http://www.isrcg.org/recommendations/buy-meldonium-online-no-rx/> symptoms diverticulitis order cheapest meldonium and meldonium</a>.
Current standing and new developments in Peyronies illness: medical, minimally invasive and surgical remedy choices. Because there's a high incidence of subclinical neck illness, radiation doses between 50 and 60 Gy are used to electively deal with the neck. Detection of postnatal melancholy: Development of the ten-merchandise Edinburgh Postnatal Depression Scale <a href=http://www.isrcg.org/recommendations/order-alesse-online-no-rx/> birth control cramps alesse 0.18 mg with amex</a>. It ensures consistency of care among the giant number of clinicians in our Newborn Center and at multiple areas within the Houston space. For practical functio
GeorgBarbots | 18-06-21 08:53 Refer to Chapter physicians changing their follow, such that they three, Section 10 for an outline of potential not prescribe the beforehand accepted sources of bias. The number of glutamate residues current is involved in the regulation of folate-dependent metabolism. It is a strong hyperlink amongst micromaximum level of all samples of tea over monitored vitamins of crops, animals and humans and the absorption period <a href=http://currentsky.com/learning/course32/> erectile dysfunction vacuum pump price buy genuine vpxl online</a>.
Risk evaluation for and techniques to scale back perioperative pulmonary problems for patients undergoing noncardiac-thoracic surgery: A guideline from the American College of Physicians. B 6 An endometrial biopsy obtained with the resectoscope utilizing a cutting loop (Gynecare Versapoint , Ethicon Endo-Surgery Inc. Brown has type O blood according to the model what surface antigens does she have on her red blood cells four <a href=http://currentsky.com/learning/course40/> blood pressure medication during pregnancy purchase generic midamor from india</a>. Moreover, he looked very tall and strong and, due to this particular phenotype, his classmates incessantly mocked him, so he usually reacted aggressively. Answer is 4 Apley,s orthopedics 8th ed/ 230 Maheshwari essential orthopedics 2nd ed/51 (table 10. Inhalation publicity of male Fischer 344 rats for 4 hr to 3 aluminium flakes, at aluminium concentrations of 10, 50, 100, 200 or one thousand
Redgescant | 13-06-21 23:33 Lowest revenue group having low protective foods suffer type rickets and nutritional anemia. Bacteria and mycoplasmas are commonly concerned together in the pathogenesis of pneumonia in goats and sheep. Ocular Alignment in Infancy Ocular deviations through the first month of life do not essentially indicate an abnormality <a href=https://www.piramalcriticalcare.com/wp-content/medical-research/report702/> prostate yeast infection purchase penegra</a>.
Austria made no reservations to the Convention and the implementing legislation offers effective and beneficiant mechanisms for processing Hague Convention requests. In general, retinoic acid seems to in?u man melanocytes, it could possibly alter cell shape, suggesting that ence, in a focus-dependent manner, cell lineage retinoic acid could act on cytoskeleton proteins (397, 543). Some of the common ailments of titis can be caused by staphylococcal, otolaryngologist interest are described here <a href=https://www.piramalcriticalcare.com/wp-content/medical-research/report705/> pain treatment mayo clinic cheap 600mg motrin with mastercard</a>. In addition, long-time period studies have shown that the benefts of calcipotriene remedy had been maintained for up to one yr <eleven>15]. There ought to be education on the nature of melancholy and its therapy choices and will embrace the next: a. The third issue concerns the differentiation from a dysfunction secondary to extreme deafness or to some specific neurological or different str