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

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

Афоризм
Слово не воробей, в лес не убежит.
 
Поиск


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

Rufustwels | 12-03-23 00:40
For these blood cells to do their jobs, you need to have enough of each type in your blood. While smoking is among the primary relationship of hypothalamic-pituitary glandcauses of infertility and many of the ovarian hormones. It is discovered that the mitochondrial content is immediately proportional to the quantity of energy one cell is required to generate and expend antibiotics used for acne rosacea [url=https://sports.kdsg.gov.ng/wp-content/buy/Colchicine/]colchicine 0.5 mg buy overnight delivery[/url].
If the for the analysis of drug-induced eruptions and a test is adverse, 10-fold growing concentrations skin biopsy may not definitively exclude 35 are used sequentially till the take a look at is optimistic or the alternative causes. This advancement In Vivo services enhances the applying of sperm cryopreservation as a colony management tool. Primary sclerosing cholangitis and autoimmune cholangiopathy causing biliary cirrhosis treatment 4 water [url=https://sports.kdsg.gov.ng/wp-content/buy/Reminyl/]buy reminyl 4 mg[/url]. Providing appropriate dietary help stays a big problem in infants with well being problems. Am J Kidney Dis 1995; 25: research: comparison of ordinary versus intensied extended dialysis for 1721. A clinical trial* is the preferred choice for sufferers who relapse following a bone marrow transplant* erectile dysfunction diabetes medication [url=https://sports.kdsg.gov.ng/wp-content/buy/Dapoxetine/]generic 60 mg dapoxetine amex[/url]. Prospective, ran


Murakven | 01-02-23 09:19
Available evidence suggests some relationship between the evolutionary place of a species and its conjugation mechanisms. Motor fibers are axons of motor neurons in motor nuclei of the perspicacity stem and end skeletal muscles of the chairperson and neck. They the effectiveness of recognized that different sufferers, at totally different not amenable to methadone grew, instances, may wish vastly totally different companies symptoms kidney pain [url=http://dtekerala.gov.in/buy/Olanzapine/]buy generic olanzapine 2.5 mg on-line[/url].
Although essential because of managed-care constraints and continued development 3 four Chapter 1 of capitated contracts, this method contributes to the and control) and using applicable diagnostic procedifficulties in maintaining properly-trained staff in a few of dures accompanied by a complete understanding of the the specialty areas of microbiology. Then there are other individuals which the medical group calls Type A personalities. Wallden K, Stenmark P, Nyman T, Flodin S, Graslund S, Loppnau P, Bianchi V, Nordlund P erectile dysfunction newsletter [url=http://dtekerala.gov.in/buy/Cialis-Black/]cialis black 800 mg buy fast delivery[/url]. Distinct behaviours, which can come to pass in a manic happening may, when they are exhibited repeatedly in the longer path of a bipolar pandemonium, seem "histrionic", "borderline", "narcissistic" or even "antisocial". Unlike the shapeshifting talents of Mystique, Copycat's morphing appeared to go to the


proverpost | 23-01-23 21:47
Один из крупнейших сайтов отзывов в России и СНГ. Тут уже добавлено огромное количество предприятий и товаров -
https://www.ted.com/profiles/41075418/about


Сервис позволяет оставить отзыв о компаниях, товарах, местах, еде, сайтах и многом другом в один клик.
https://yurgorod.ru/vopros/30328/


Большая база уже написанных отзывов и разделов, но часто отзывы удаляют, поэтому запаситесь терпеньем.
https://club4x4.ru/forum/viewtopic.php?f=17&t=76151


На данном сайте в основном пишут отзывы о заведениях и местах, но база не очень большая
https://www.airlines-inform.ru/personal/user/?UID=64097


obango342desu&^


CyrusAngevezer | 22-01-23 05:59
In 1913 Tanret reported the isolation is Sunsoysoy bean loaf An completely new kind of bread of sucrose and a tetrasaccharide stachyose from soy beans. A second dose two weeks after the primary is typically needed if the an infection has not cleared (which can occur when you swallow some eggs after taking the medication). Second,neither timed urine collections nor protein-to-creatinine ratios were measured,and thus the dipstick take a look at result was affected by the state of diuresis in addition to the magnitude of proteinuria gastritis quizlet <a href=http://www.trellisbio.com/buy/Reglan/>reglan 10 mg without prescription</a>.
The situation of the patient and the rationale for admission ought to deter mine the extent of the bodily examination carried out and the laboratory stud ies obtained. Although the absence of human pregnancy experience prevents a full evaluation of the embryo–fetal risk, there is no proof that other parasympatholytics. Cyanosis, dyspnea and intensive ache within the half, which is the placement of pneumonia infiltration, are observed, as well as coughing with sputum treatment 1st 2nd degree burns <a href=http://www.trellisbio.com/buy/Risperdal/>risperdal 2 mg buy online</a>. Angel WingsAngel Wings Stand with arms overhead Keeping elbows to the aspect, slowly lower arms Try put your elbows into back pockets Squeeze shoulder blades together Hold 10 sec. In study 1, we enrolled 19 laboratory-confirmed case the Study patients and 38 age-matched, nei


AngirSpameseen | 06-01-23 09:57
Overall about l Supplementation of iron and folate in being pregnant is the 16% of Rh-negative women are at risk of isoimmunizabest way to forestall its deficiency, at least in ladies at tion, this risk is decreased to 1. The relative frequency of cluster-headache ciated with transitory neuropsychologic disturbances. For the livestock commodities, the following assumptions were used: (1) all alachlor metabolite residues found within the livestock animal metabolism research are residues of concern and (2) the share restoration of the analytical method in livestock commodities is based on the share of metabolites recovered in metabolism research diabetes diet plans free <a href=https://cemalta.gov.mt/order/Precose/>precose 25 mg buy generic online</a>.
What is the natural historical past Grouped vesicles on an erythematous of herpes an infection. Patients who're pyridoxine nonre supplementation of folic acid and, if serum ranges are low, sponders have to be treated with a dietary reduction in nutritional vitamins B6 and B In the United States, cereal grains are methionine and supplementation of cysteine, additionally from 12 fortified with folic acid. It could be as simple as admittance to a may also disapprove of certain motivations, to holy order, because you must be a wife to be able to such an extent that a brand new couple shall be serve the Queen of Wives hiv symptoms sinus infection <a href=https://cemalta.gov.mt/order/Nemasole/>proven nemasole 100mg</a>. It is a misno


ThorekShelo | 01-01-23 15:41
However, some results don't appear for hours or even If the injury is severe, the particular person may have hassle days and should last for several days or even longer. The difference between silver nitrate and chloroformic garlic extract groups had been statistically important and comparable results were observed between chloroformic garlic extract and regular saline groups. Improved biomass prepare dinner stoves have reported up to now has been the publicity period been identifed as an choice to cut back adverse and depth evaluation, precluding the demonimpacts of cooking with conventional open fres stration of an publicityпїЅresponse relationship erectile dysfunction 2 <a href=https://cemalta.gov.mt/order/Viagra-Super-Active/>viagra super active 25 mg overnight delivery</a>.
Every healthcare professional making use of these pointers is answerable for evaluating the appropriateness of applying them in the setting of any particular scientific situation. This mindset started to vary when boards of nursing petitioned state legislatures to approve diversion laws. Then, we excluded prospective studies that included hysteroscopic fibroid resection because of considerations that hysteroscopy may yield incomplete tissue for pathology (mannequin 4) allergy medicine equate <a href=https://cemalta.gov.mt/order/Quibron-t/>400 mg quibron-t purchase with mastercard</a>. Physical examination exhibits bilateral conjunctival injection, an enlarged left-sided cervical lymph node (1. The f


Yespasaliergy | 26-12-22 02:51
On common, the smo- king behaviour of African–American males produced the highest emissions and that of Caucasian American women produced the lowest. Meckel's diverticula appear in males and females at equal frequencies, however, males are three instances extra likely to develop symptomatic or difficult Meckel's diverticula. Medication utilization was not reported even if drugs (eg, anti-depressants) might affect outcomes blood pressure medication fluid retention <a href=https://qsrbn.gov.ng/buy-online/Cardizem/>cheap cardizem 60 mg free shipping</a>.
These websites are generally used right now with the usage of computerized radiographic absorptiometry, computerized radiogrammetry, and ultrasound tools. Remember this is an extremely essential step as the first objective of therapy in open fracture is to convert In open fractures: Debridement is the mainstay of therapy an open wound into closed wound. Bad: the North and South fought the Civil War for a lot of causes, some of which have been the identical and a few completely different knee pain treatment guidelines <a href=https://qsrbn.gov.ng/buy-online/Cafergot/>cafergot 100 mg online</a>. This illness is answerable for in depth economic losses Laboratory Results: None. Hepatitis B virus is unfold parenterally and by sexual contact and may cause acute hepatitis, persistent hepatitis, cirrhosis, and hepatocellular carcinoma. Associate Professor and Associate Professor Chief, Section of Cardiology Anesthesiology Barbara J


Mirzokix | 24-11-22 23:44
Failures of rotation (Chronic peptic ulcer rarely give rise to gastric carcinomas, 1. A healthy, term infant (birth weight and intercourse not specified) was ultimately delivered (5). Most business consultants also distinguish worth for it; the provider by selecting it between radical and incremental innovation, though the excellence isn't over different therapies; and the affected person by all the time very useful erectile dysfunction statistics us <a href=https://www.skip.edu.hk/introduction/section4/Aurogra/>generic aurogra 100 mg free shipping</a>.
The anvil is then withdrawn from the bowel and secured with a handbag string suture earlier than finishing the anastomosis in accordance with the usual operative steps of the KnightGriffen method. Although each effort has been made to make sure that therapy and different information are presented precisely on this publication, the final word duty rests with the prescribing doctor. The surgical case is canceled, and the donor coronary heart is re-routed via the organ-sharing network to the next suit- A medications zanaflex <a href=https://www.skip.edu.hk/introduction/section4/Septra/>generic septra 480mg with mastercard</a>. This sort of powder could be light, dark, or fuo opaque adhesive gel lifters, usually black or white; and rescent and utilizes the ferromagnetic properties of iron silicon-type materials which are spread onto the surface powder mixed with pigment powders. Idiopathic focal unexplained adult nephrotic syn


Jerekshovitomo | 05-11-22 22:00
Disadvantage - the suturing is tough - Shearing of the tissue occurs - the repaired wound tends to be pucked. Sometimes a nosebleed wants extra remedy, corresponding to flling the nose with gauze or a balloon to cease the bleeding. The п¬Ѓrst type of formulation <>4, 26, 36, seventy three] doesn't keep in mind any histological constituents and attempt to describe the global mechanical habits of the tissue with out referring to its underlying microstructure anxiety and panic attacks <a href=https://sja.pi.gov.br/part2/Luvox/>order luvox 100 mg online</a>.
Neonatal Neurodevelopmental Follow-Up Program Early antibiotic exposure and antagonistic outcomes in preterm, of cup feeding as a supplemental, alternative feeding methodology Connecticut Children’s Neonatal Neurodevelopmental Follow-Up very low start weight infants. Ischemic tissue oxygen capacitance after hyperbaric oxygen remedy: a new physiologic concept1997, Plast Reconstr Surg, Vol. But iron-oxidizing bacteria, which are found all over the place in the environment, usually colonize the filtration media, and will find yourself being accountable for the majority of iron removal hypertension and headaches <a href=https://sja.pi.gov.br/part2/Microzide/>discount microzide 25mg without a prescription</a>. It is way less widespread in less developed areas of sity epidemic spreads worldwide, there's great concern that the world; nevertheless, the mortality fee in these areas is larger the global incidence of endometrial mos


MiltenZib | 27-10-22 17:52
Wound therapeutic could also be prolonged by overseas our bodies, an infection, ischemia, diabetes, malnutrition, or scurvy. The commenter believes that, from an actuarial perspective, this methodology isn't valid since the complete rate obtained by summing the separate Part A per capita rate and Part B per capita price does not yield the identical end result as the speed calculated utilizing beneficiaries with each Parts A and B. Other potentialities include a sponAs a result of frequent bleeds, hemophilia sufferers usually have taneous germline mutation in the otherwise regular allele of a debilitating and progressive musculoskeletal lesions and deforheterozygous female or a disproportional inactivation of the mities and neurologic defciencies after intracranial hemorX chromosome with the traditional gene, termed excessive lyonization medications known to cause tinnitus <a href=https://www.tpocr.com/med/vastarel/>quality vastarel 20mg</a>.
This reviewer additionally pointed to the similarity between the ends in the uncovered groups and knowledge from historical controls as a further issue that weakens the findings. We have assumed that these processes are primarily based on a change within the section state of the liposome membrane. Effects of methylphenidate on intelligence and a spotlight elements in boys with attention-deficit/hyperactivity dysfunction insomnia zippy <a href=https://www.tpocr.com/med/sominex/>cheap sominex line</a>. Teaching He ought to be capable of p

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