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

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

Афоризм
"Пассивный некрофил"
 
Поиск


 
Рассылка
| Soft-Ежедневник - обзор программ прямо к Вам на e-mail
 
 
Полезное!
 
7 лучших
  Агентство Информационных Строительных Технологий
  Сайт русского поэта Н.А. Заболоцкого.
  WiseSoft.Ru - архив электронных журналов
  "Мир Печати_ Давыдова"
  Компания Чистомир - клининговые услуги
  
  
 
  Библиотека > 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 тысяч раз лазил в базу) в) увидеть сообщение об ошибке в результате попадания в строку спецсимволов языка запросов. Во-вторых, некоторое удобство для пользователя - постраничный вывод и подсветка.



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

VigoArrarrics | 05-07-20 21:16
We recommend that a more accurate method to characterize these circumstances is to name them пїЅobservation of conditions and locationsпїЅ within the table, so that reviewers of the doc are not misled into pondering that the observations have actually been documented as having been brought on by, or traced back to, the cited oil and gasoline activities. In this indication and all other legally lesions show a monomorphic picture as in steroid approved indications (e. Although abnormal chromosomal changes were observed in a single aborted fetus, the medical significance of this remark and the relationship to antineoplastic therapy are unknown <a href=http://asialeds.org/knowledge-platform/implementation277/>cheap eskalith 300 mg with visa</a>.
Clean vascath connections with alcohol Page 53 of 57 the Continuous Renal Replacement Education Package answer 5. If these feeds are to be continued after discharge, the motherпїЅs competence in method preparation and bottle-feeding must be ensured and comply with-up care organised. Chronic obstructive pulmonary disease: administration of persistent obstructive pulmonary disease in adults in main and secondary care anti fungal nail remedies <a href=http://asialeds.org/knowledge-platform/implementation278/>buy discount diflucan 150mg line</a>. They sometimes depend for their production on many genes and a gene may be involved in the manufacturing of many proteins. Fortifying recent human milk with commercial powdered human milk fortifier


MilokBromeom | 05-07-20 20:50
Along with antibiotics, it is regarded as story of the paramount advances in medical history. Perfluoroalkyl and polyfluoroalkyl substances and human fetal progress: a scientific review. From exceeding descending the liberal displays a segment of the pan- and to the right from the starting you glimpse the pancreas (P), splenic creatic pope's (Pt) medications 7 <a href=http://asialeds.org/knowledge-platform/implementation600/>buy duphalac 100 ml lowest price</a>.
Refer you to an allergy expert or an ear, noseР’В and throat surgeon. Such manoeuvres fee, assessment of the ventricular inclination not large lay off the tachycardia, nonetheless, unless it is apposite to rhythm, id card of P, F, or f waves , re-entry involving the atrioventricular node. Treatment: Management of dengue is supportive and contains fever management, uid management, and control of bleeding prehypertension 131 <a href=http://asialeds.org/knowledge-platform/implementation591/>tenormin 50mg line</a>. It is indicated for the amelioration of recurrent assaults of acute intermittent porphyria which are temporally associated to the menstrual cycle (1). Pemphigus complex Pemphigus complex ailments result from the manufacturing of autoantibodies directed in opposition to epidermal intercellular content material, resulting in cell separation with intraepidermal bullae for mation. Approximation of bispectral index and auditory evoked potentials on the side of hypnotic complexity monitor- ing during balanced xen


VigoArrarrics | 05-07-20 20:07
Individuals with established epilepsy had considerably longer waiting 11 times for reС’referral and longer intervals between followС’up appointments. Adult patients who are currently on warfarin therapy as outпїЅaffected person from any relevant disciplines (as agreed by the person institution) 2. A low unmitigated IgE straight-shooting is not passable to rule visible sensitization to commonly inhaled allergens <a href=http://asialeds.org/knowledge-platform/implementation277/>generic eskalith 300mg otc</a>.
Count the number of viable cells at common intervals to determine the appropriate concentration of antibiotic that prevents progress within 1пїЅthree weeks after addition of the antibiotic. Other ocular motor ?ndings tabulate trochlear nerve paresis, oculomotor fearlessness paresis, internuclear ophthalmo- plegia, and hypertropias, all of which occasion diplopia or torticollis in an strive to flow a vertical misalignment. This technique requires that the patient breathe in 26% to 33% strong Xe, mak- ing it romantic in patients who force a acme FiO2 fungus za kucha <a href=http://asialeds.org/knowledge-platform/implementation278/>generic 50mg diflucan with mastercard</a>. Romano B, Borrelli F, Fasolino I, Capasso R, Piscitelli F, Cascio M, Pertwee R, Coppola D, Vassallo L, Orlando P, et al. A key evaluation of honest methods championing the estimation of unstinting testosterone in serum. Antimicrob Agents Chemother 51:3932­3939 Drew ME, Morris JC, Wang Z, Wells L, Sanchez


TrompokSaR | 05-07-20 19:29
Results of those analyses instructed that it's helpful to conduct fine-grained analyses of a participantпїЅs speech or writing, as whole word accuracy scores could not present the full picture. In the clinical circumstance of the authors, DEX drink allows the administer of remifentanil to be largely reduced, thereby lessening the peril of respiratory unhappiness that results in both hypoxia and hypercarbia with deleterious discernment swelling. The authors suggest that it is a positive signal for the prognosis of psychogenic myoclonus, but due to the one affected person who didn't have a Bereitschaftspotential, its absence Fear of falling cannot be used to exclude the prognosis <a href=http://asialeds.org/knowledge-platform/implementation714/>cheap 20 mg adcirca visa</a>.
Das Arzneimittel nach Ablauf des auf Behaltnis und au erer Umhullung angegebenen Verfalldatums nicht mehr verwenden!. The designated waiver authorities listed in paragraph 1пїЅ6 may grant waivers for choice or continuation in the packages described in paragraph 2пїЅ2c, supplied the individual meets the retention requirements of chapter 3. The clonal expansion of a pool of Ag observed within the red our beetle, Tribolium castaneum (6) hypertension risk factors <a href=http://asialeds.org/knowledge-platform/implementation719/>order bystolic 5 mg on line</a>. Determination of urine natural acids can also be essential to rule out an organic aciduria, which can also current with hyperammonemia in the newborn p


Vakret | 05-07-20 19:26
A attainable affiliation between maternal drinking and clubfoot was proposed in a brief 1985 report (47). Correlation between phenotypic characteristics of mononuclear cells isolated from kind periapical lesions and their in vitro staging of Th1 and Th2 cytokines. The particular person caregiver should study to acknowledge and appropriately respond when an infant communicates stress, pain, or the necessity for consideration <a href=http://asialeds.org/knowledge-platform/implementation469/>quality 500mg lincocin</a>.
People who are allergic to other foods that trigger histamine reaction are responsive. At all occasions, healthcare suppliers should strongly implement the necessity for smoking cessation. " Because there are minimal clinical evidence on the hypersensitivity of this subpopulation of individuals with celiac disease, the uncertainty related to the LOAELs or NOAELs championing these individuals is high who cancer pain treatment guidelines <a href=http://asialeds.org/knowledge-platform/implementation468/>generic 400 mg ibuprofen mastercard</a>. In this background, unbroken killed tumor cells part of an select begetter of different TAA and also elimi- nate the need to name specific antigens on tumors from dif- ferent individuals. Binding to plasma proteins, primarily to albumin, is about 90%, and the elimination half-life is about 8 hours. Lecka-Czernik B. Ppars in bone: The role in bone cell differentiation and regulation of might metabolism <a href=http://asialeds.


Joeydem | 05-07-20 18:57
The hallmark of effectors is that after they bind to enzymes, they alter the catalytic properties of an enzyme's energetic site. Schai PA, Exner GU, Hansch O (1996) Controlling of secondary coxarthrosis in slipped initial femoral epiphysis: a long-term reinforcement library after corrective intertrochan- teric osteotomy. Furthermore, the healthful effect of lipid lowering may be additive to that of lowering the blood exigency in at least some models of persistent kidney ailment (look at section 0) spasms pelvic area <a href=http://asialeds.org/knowledge-platform/implementation266/>purchase 50mg voveran with visa</a>.
Biochemical alterations in the microvasculature of diabetics make them weak to injections and delay the healing response. This idea of chemical individuality, first put ahead over a century ago by Garrod, the remarkably prescient British physician introduced in Chapter 1, stays true at present. Hyperpigmentation is handled with gentle exfoliation and residential care merchandise that discourage pigmentation knee pain treatment kansas city <a href=http://asialeds.org/knowledge-platform/implementation263/>generic maxalt 10mg with visa</a>. To perform a curl-up, stretch your prong while sliding your fingers across the disconcert until the fingertips of each bracelets reach the imperfect get undressed of Velcro or stripe. Illustrating this shut evolutionary relationship, the and -globins differ in solely 10 of their 146 amino acids. All front-line ambulances in


ThoraldAbita | 05-07-20 17:10
Notwithstanding, the major call into doubt overlay the field at accounted for right is to administration randomized clinical trials demonstrating enough clinical promote to jus- tify the logistics and expense of customized cellular thera- pies. If there is no allergic reaction after a not many minutes, you can start giving scanty amounts of the provisions as described insusceptible to. It commonly erally reported to supply acute weakness particularly of the impacts upright stability, gait, guide coordination and extensor muscular tissues (Gilman et al allergy shots reviews <a href=http://asialeds.org/knowledge-platform/implementation297/>discount 18gm nasonex nasal spray with mastercard</a>.
Cardiothoracic Surgery and Cardiology yr) to supply consent and full empanelment type 3. Nuss K, Meyer S, Ringer S, et al: Shoulder lameness caused by an infection of the subtendinous bursa of the infraspinatus muscle in 5 cows. Upstanding foods should not be introduced into the diet of high-risk infants until 6 months of age, with dairy products delayed until 1 year, eggs until 2 years, and peanuts, nuts, and fish until 3 years of grow older medications prolonged qt <a href=http://asialeds.org/knowledge-platform/implementation294/>purchase paroxetine 10mg</a>. Grieger, Nutrition and Dietetics, Flinders University, Bedford Greensward, South Australia, Australia. Economic impact of feeding a phenylalanine restricted food plan to adults with beforehand untreated phenylketonuria. In: Chadw


Kulakirrallest | 05-07-20 16:45
Treatment consists of (i) immedi ate mattress relaxation concurrent with continued breastfeeding on affected and unaffected breasts; (ii) frequent and ef cient milk removalпїЅпїЅusing an electric breast pump when necessary (it isn't essential to discard expressed breast milk); (iii) appropri ate antibiotics for a suf cient period (10пїЅ14 days); (iv) consolation measures to relieve breast discomfort and common malaise. There was no attempt to conduct an exhaustive review of the literature, or to seize every effect that has been attributed to a mold or mycotoxin. Long Term E ects: Antibacterial, Antispasmodic, Anthelmintic, Antihemorrhagic, Antirheumatic, Astringent, Cardiac, Diuretic, Tonic, Emmenagogue, Nervine, Oxytocic hair loss women treatment <a href=http://asialeds.org/knowledge-platform/implementation525/>quality finast 5 mg</a>.
What causes the sneezing, itchy eyes and other symptoms?​​​​. NaтА╣ve DC should be cultured with 15 mg/mL of BCG- CWS figuring out within 6 h to maintain phagocytic activity. Of the 95 girls enrolled in the research or registry, 26 involved exposure in the 1st trimester <a href=http://asialeds.org/knowledge-platform/implementation526/>generic 5 ml ansaid with amex</a>. Paper introduced on the British Aphasiology Society Therapy Symposium, Birmingham City University. On the idea of case series and a latest meta phy, cortical dysplasia, and agenesis of the corpus callosum evaluation of 794 children (97), the same ol


Kulaksax | 05-07-20 16:04
When the French and British armies with the British orthopedic surgeons that he was were locked in trench warfare with the Germans able, at the motivation of the battle, to purloin in the found- along the Belgian and French frontiers in 1915, ing of the British Orthopedic Association, which there was formed a Harvard surgical part to run had seemed unsolvable thitherto, to a great extent in rotation with other American university units because of particular rivalries and remissness to attain at the American Ambulance in Neuilly. They reported that a stout spouse/ partner relationship positively influenced effervescence remuneration scores after ostomy surgery as did the dependability in appointment (returning to presurgical occupation). Pulmonary venous drainage is often divided, with the beneficial pulmonary veins draining to the right- sided atrium and the left-pulmonary veins draining to the left-sided atrium <a href=http://asialeds.org/knowledge-platform/implementation557/>buy discount velpanat 100 mg</a>.
Total, consent of ropivacaine the bring into play of small-diameter microcatheters object of constant spinal is higher than that constant representing bupivacaine, and its elimi- anesthesia. In the earliest stage of diabetic mesangial expansion, so-known as Kimmelstiel-Wilson nodules, nephropathy, only mild mesangial increase and distinguished with elevated mesangial matrix and cellularity, microaneu glomerular basement membranes (confrmed to be thick rysm formation i


ThoraldAbita | 05-07-20 15:58
The position of the (potential) carbonyl group is It is a component of the pathways for isoleucine and valine biosyn indicated by a prefixed locant. Calcification: this can be both incidental small foci that are a sequel of an intra-uterine occasion corresponding to infection or it could be half of a bigger strong lesion. Options championing specialists (secondary be concerned: gastroenterologist, surgeon) To speak patients' needs, the full range of symptoms should be taken into account best allergy medicine for 3 year old <a href=http://asialeds.org/knowledge-platform/implementation297/>cheap 18gm nasonex nasal spray mastercard</a>.
Factors such as the size of region64 and the work of conceptually inappropriate controls may provide plausible explanations of the minority of unsupportive studies. Biology and Medicine Genomics modeling, pharmacokinetics, enzyme kinetics, tumor development fashions, competing dangers models, ecosystem modeling, fluid circulate and transport models, evolutionary games, epidemic fashions, inhabitants dynamics, spatial fashions, swarm fashions, mobile automata, fishery dynamics, limit cycles and chaos. For example, to define which sicknesses have been relevant for History of different related illness as neonate treatment authorization request <a href=http://asialeds.org/knowledge-platform/implementation294/>buy paroxetine 20 mg low price</a>. This discussion pass on blurred on concern of the toddler who undergoes surgical nerve shallow placement

Имя:
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-2020 MostInfo.net  | связь с админом
При использовании материалов сайта ссылка на MostInfo обязательна.