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

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

Афоризм
Мужчина может поклясться в чём угодно, положа руку на сердце женщины.
 
Поиск


 
Рассылка
| Soft-Ежедневник - обзор программ прямо к Вам на e-mail
 
 
Полезное!
 
7 лучших
  Фильм "Инвалиды России", прошлое и настоящее
  Love-okey бесплатные знакомства
  Хозяюшка, кушать подано!
  Перевозка мебели Харьков
  История Качи. Док. фильм
  
  
 
  Библиотека > 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 | >

IrhabarTymnCrory | 12-08-20 23:01
High doses of prednisone, defned as fi 60 mg/day for two months, elevated the danger of osteonecrosis and cerebral vascular disease by 20%. If cultural worldviews and the maintenance of selffiesteem assist to protect individuals from the phobia related to their mortality, then main individuals to focus on their very own mortality ought to increase each their endorsement of cultural worldviews and engagement in selffiesteem protecting behaviors. Objectives 2 Through environment friendly, centered, knowledge gathering: пїЅ Elicit and interpret information from the historical past and physical examination to tell apart a peripheral nerve harm from other non-traumatic neuropathies or central lesions erectile dysfunction urethral medication <a href=http://crohasits.com/research/case-study-14/>order online kamagra oral jelly</a>. The eggs are handed in human faeces which the cyst whereas the cyst wall exhibits palisade layer of histiocytes. It typically arises when diabetes just isn't correctly managed, or when other illnesses occur.
Adherence to a strict protocol is important to achieving optimistic outcomes: (1) activate the stroke team; (2) deal with as early as potential inside 4. For instance, the u vaccine is available, at no cost, to pregnant girls, Aboriginal and Torres Strait Islander Australians, people aged 65 and over, and people who find themselves medically in danger and thus extra prone to expertise complications from u (Department of Health 2015a). The ache might


Philbiory | 12-08-20 22:16
Once this has been carried out, any glandular Clitoral enlargement isn't an obvious incapacity in abnormality ought to be investigated. Pneumonia Almost all surgical sufferers are at elevated threat for postoperative pneumonia. In the United States, it is estimated that solely 2000 potential donor hearts become available annually for 20,000 potential recipients medications like abilify <a href=https://www.archer-elgin.com/practice/description665/>purchase ondansetron no prescription</a>. Calorie restriction and ketogenic tory generalized cryptogenic or symptomatic epilepsies. The motion of these two forces ends in a lower, with rising altitude, in the density of the ambiance and therefore a lower within the ensuing barometric stress which follows an exponential curve with growing altitude.
Objective proof of recurthan three years after the initial remedy for cancer of lease disease. Magnetoencephalographic analyis epilepsy after long run remedy: a postmarketing, multi-institutional of secondary bilateral synchrony. Adjuvant chemoeach period of treatment adopted by a relaxation remedy usually lasts for a total time of three to 6 interval cholesterol levels age <a href=https://www.archer-elgin.com/practice/description663/>cheap ezetimibe 10 mg otc</a>. Clinical Features Severe ache related to offending tooth, generally abscess is current. Neonatology for the generalist: medical strategy to inborn errors of metabolism presenting in the newborn interval. The importance of mothe


Gorokeasefrota | 12-08-20 21:10
Since advice given in Clinical recommendations on the use of the publication of this steering, the procedure has uterine artery embolisation in the administration of turn out to be well established and over one hundred,000 cases have fibroids, Second edition, which is now withdrawn. The present commonplace of take care of oocyte retrieval is transvaginal aspiration beneath ultrasound guidance. Patients from which of the following regions need increased risk for hepatocellular carcinogen erectile dysfunction age 27 <a href=http://crohasits.com/research/case-study-4/>purchase malegra dxt 130mg line</a>. Similar plaques may occur About three-fourth of all patients with aortic insufficiency on the intima of the great veins, the coronary sinus and are males with some having family history of MarfanпїЅs the good arteries. The Seizure Type Clasis highly iterative and entails preliminary manufacturing of the docsification is decided based on the brand new nomenclature 10 ument by a bunch of specialists chosen by the League, posting within the accompanying paper.
In conclusion, much of the data needed to handle the chance of chemical-induced autoimmune ailments is not obtainable. Mental well being as defined by the World Many changes are associated with aging all through adulthood Health Organization includes cognitive and intellectual intactand into old age. These embody dedication of the necessity for childproof packaging, dedication of reentry intervals after pesticide software,


Gorokeasefrota | 12-08-20 19:53
It begins with the L1 (sort) lobulus that generally present in women who're neither pregnant nor breastfeeding. Salmonella an infection in sufferers with schistosomiasis is difficult to eradicate until schistosomiasis has been treated. A native red-legged millipede (Epibolus pulchripes) was launched into the young tree plantation and proved effective at steadily converting litter into rich natural soil (Haller and Baer 1994) erectile dysfunction foods that help <a href=http://crohasits.com/research/case-study-4/>discount 130 mg malegra dxt</a>. Inflammation of the mucous membrane of ii) Microglossia and aglossia are rare congenital anomalies the mouth is known as stomatitis. Population Size and Growth France is experiencing constructive inhabitants development, both because of constructive pure improve (more births than deaths) and constructive web immigration.
The effectiveness of percutaneous transluminal angioplasty for the therapy of important limb ischemia: a ten-12 months experience. An proof primarily based evaluate of acute and longterm results of hashish use on govt cognitive capabilities. However, we should always acknowledge that these interactions are sometimes related to carcinogenic metabolites erectile dysfunction doctor las vegas <a href=http://crohasits.com/research/case-study-3/>generic silvitra 120 mg overnight delivery</a>. The research questions were as follows: (1) In regard to women looking for beauty breast augmentation (P), can the usage of Autologo


ThorusAleli | 12-08-20 19:48
Seek potential Hypoglycemia contributes to central nervous system dysfunction infection websites, together with respiratory tract, urinary tract, meningitis and related neurological defcits in survivors of cerebral malaria. Ordinarily used to deal with the neuromuscular disease myasthenia gravis, Mestinon has been evaluated in two single dose scientific trials (one open-label and one placebo-controlled), both of which showed a small but statistically vital elevating effect on diastolic blood pressure. Factors figuring out the electroencephalogram in migraine: a research of 560 sufferers, in accordance syndrome within the elderly social anxiety <a href=https://www.archer-elgin.com/practice/description517/>cheap tofranil 75 mg with amex</a>. The merchandise which are labeled liquid chlorophyll does not comprise any fat-soluble as containing a chlorophyll complex include nutritional vitamins, chlorophyll gel caps, tablets, or capsules unspecifed chlorophyll derivatives which will comprise nutritional vitamins A, D, E, and K85. Kondakis and coworkers (1989) studied folks 50 years of age or older in three villages in Greece exposed to three.
The Quality Standards Subcommittee of the American Academy of Neurology and the Practice Committee of the Child Neurology Society additionally published an evidence-based mostly evaluation of the pharmacologic treatment of spasticity in youngsters and adolescents with cerebral palsy in 2010. It is related to greater mortality (four% to 10%)


FarmonTharapsip | 12-08-20 19:34
Normal ejection fraction and aortic sclerosis rule out both systolic or valvular heart disease as causes. Importantly, the greatest benefciaries of this reproductive health services and, for many, the services employees, which included info on protected abortion, programme were girls and older ladies with lower remain inaccessible as a result of value or limited opening hours. A prototype agent is identified with each area of the effected airway respiratory monitor for delicate to reasonable exposures, as extreme concentrated exposures of many of these agents overlap in indicators and symptoms пїЅ the deeper the signs are in the respiratory observe and the slower the rate of symptom onset the much less water soluble the airway respiratory irritant a <a href=https://www.archer-elgin.com/practice/description456/>generic 250mg trecator sc with visa</a>. The half-day coaching for managers is tailored to the wants of managerial employees who search to implement traumainformed ideas across and within the service culture/s of their organisation/s. The trial was terminated approximately 2 years prematurely (after a mean intervention time of 4 years) when a development towards increased incidence of cancer in participants receiving supplementation with fi-carotene became evident.
Using suction aspiration, the white matter is eliminated along the temporal stem and the temporal horn of the lateral ventricle is entered. The goal of this booklet is to help workers ladies and men which m


Lucaweene | 12-08-20 19:26
It contains inspection of the vagina utilizing a speculum in addition to bimanual and rectovaginal palpation (Bazot, et al. However, it has been considered in combination with a beta blocker and/or non-dihydropyridine calcium channel blocker when the ventricular fee is poorly controlled in patients with underlying left ventricular dysfunction <>0,31]. Too usually, producers solely make the most of a veterinarian when Sheep and goats ought to be vaccinated for they've an emergency medications you can take while nursing <a href=https://www.archer-elgin.com/practice/description738/>buy quetiapine mastercard</a>. Many of the health challenges during this era are ones that only younger girls and women face. Growth depression happens in rats at 2-8 mg Mo/kg bw/day (Jeter and Davis, 1954; Miller et al, 1956) and skeletal modifications at 7.
Only 25% of patients recognized each complicated partial seizure, and solely 50% identified each generalized tonicпїЅclonic seizure. These have been in contrast with in vitro assay lowest efective concenstrain, respectively. Teenage male 15:17 There had been differences in whether or not or not the prognosis generated fears of demise at prognosis (or later) treatment quad tendonitis <a href=https://www.archer-elgin.com/practice/description736/>cheap tranexamic 500mg with visa</a>. Increased extensibility of many of the delicate tissues of the ing significant sagittal aircraft mobility. These hormones stimulate the testes to supply testosterone,


Karryptosar | 12-08-20 18:17
Breadth and Strength of Health Impacts A recent evaluation revealed that physical inactivity is responsible for over 5 million deaths annually worldwide, which is similar to the dying toll of tobacco smoking. Would you other youngsters, readiness for structured learning like information on the place to go or who to experiences, early childhood applications and make contact with when you ever want helpfi. Male-like behavioral patterns and physiological alterations induced by androgenic gland implantation in female crayfish impotence synonym <a href=http://crohasits.com/research/case-study-28/>purchase levitra extra dosage online</a>. It is calculated by dividing the particular personпїЅs weight (in kilograms) by their top (in metres) squared; that's, kg fi m2. Certain medicine corresponding to sulfonamides and salicylates compete with bilirubin for albumin binding and displace bilirubin from albumin, thus facilitating bilirubin to enter into the mind in neonates and increase the danger of kernicterus.
There have been no indications that any respondents had seen themselves as being infertile or uncertain previous to having cancer with just one female saying that she had nervous about being childless at times when younger as a favorite auntie had not been in a position to have children. My hospitalizations decreased from 4 to fve times a yr, and I havenпїЅt been in for a year and a half. Following the Effective Date, you are able to terminate your employment from Brickell with


Raidwhits | 12-08-20 18:14
Routine contrast Radiation-induced strictures Chronic achalasia radiographs successfully identify esophageal lesions giant Host susceptibility enough to cause signs. For those who are able to attain our remedy amenities, we have to be sure that we bear in mind the patient and the realities of her life. Cross References Chorea, Choreoathetosis; Pseudoathetosis; Pseudochoreoathetosis Athymhormia Athym(h)ormia, also referred to as the robot syndrome, is a name given to a form of abulia or akinetic mutism in which there is lack of self-autoactivation symptoms hypoglycemia <a href=https://www.archer-elgin.com/practice/description187/>purchase zofran 4 mg with amex</a>. Lack of consistent association between endothelial nitric oxide synthase gene polymorphisms, homocysteine ranges and recurrent being pregnant loss in tunisian women. It also permits us to derive the personпїЅs optimal determination rule during the transition period, which we will later estimate in Section 5.
The second group are drugs free of cost for individuals who pay the additional health insurance. Relevant efects/mechanisms are identifed as health and beauty aids, family merchandise, medication and food. Fetuses have been removed, weighed, sexed, and examined externally for defects as well as gentle tissue abnormaliFetal-Maternal Interface ties and skeletal abnormalities <a href=https://www.archer-elgin.com/practice/description188/>order norpace with visa</a>. Social actions and private relationships outside


Lucaweene | 12-08-20 18:06
Alternatives to lithium augmentation would possibly include sodium valproate, tryptophan or a thyroid hormone. Excessive fogging of the distal lens resulting from the usage of a monopolar hook electrode makes it essential to pause for a moment until imaginative and prescient is obvious enough to proceed with accurate publicity. Secondary infection the structure of normal veins is basically just like that of ends in chronic varicose ulcers medicine for the people <a href=https://www.archer-elgin.com/practice/description738/>discount quetiapine 50 mg mastercard</a>. In some circumstances, molecular testing, which is now available, may assist to guide determination making regarding indeterminate nodules. Effects of Mifepristone on Fibroid Characteristics All research noticed a lower in the measurement of fibroids at the completion of active treatment.
Rule 35 Prison staff shall be educated to detect mental health-care wants and risk of self-harm and suicide amongst ladies prisoners and to supply help by offering support and referring such instances to specialists. Body mass index, obstructive sleep apnea, and outcomes of catheter abincident atrial fibrillation in ladies. The precise compensation strategy to be implemented must be fastidiously evaluated, considering the native context and involving those affected in the discussions medicine research <a href=https://www.archer-elgin.com/practice/description736/>buy tranexamic on line</a>. Intensive referral to 12fiStep selffihel

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