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

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

Афоризм
А я подкрался незаметно! c СамиЗнаетеКто
 
Поиск


 
Рассылка
| Soft-Ежедневник - обзор программ прямо к Вам на e-mail
 
 
Полезное!
 
7 лучших
  Форум о заработке в интернет
  Центр GPS ГЛОНАСС навигации и мониторинга - НавиЦентр
  Сервисный центр
  Питомник кане-корсо DEO VOLENTE
  More then varez...
  
  
 
  Библиотека > 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 тысяч раз лазил в базу) в) увидеть сообщение об ошибке в результате попадания в строку спецсимволов языка запросов. Во-вторых, некоторое удобство для пользователя - постраничный вывод и подсветка.



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

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


Irhabararigh | 27-11-21 12:01
Carvedilol produces dose associated improvements in left ventricular function and survival in topics with chronic coronary heart failure. Product Liability Act ("Lov om produktansvar" and scientific trials the Product Liability Act (https://lovdata. If the elbow is stable, a short interval of immobilization is adopted by rehabilitation medications valium <a href=https://cemalta.gov.mt/education/cefaclor/>cefaclor 250 mg</a>.
On transabdominal sonography, the cervix could also be di usely enlarged by a hypo- or isoechoic mass, and the uterine cavity may be distended by uid and debris (hae- matometra). Food – Reporting and Interpretation of Environmental Microbiological Test Results Satisfactory microbial limits for a meals pattern will be depending on the food preparation, circumstances (uncooked, ready-to-eat, and frozen, refrigerated, shelf stable) and commodity kind. Document all patient directions and affected person understanding or demonstration appropriately in Epic symptoms thyroid <a href=https://cemalta.gov.mt/education/procyclidine/>cheap procyclidine 5 mg</a>. Exploration Stage Steroid use may be viewed as a search for a aggressive edge in athletics. The subsecond- Left little 10 1 ary was to the proper of the secondary and represented the ridge counts for loops or ridge tracing for whorls in the the first was expressed in ratio type, with the numera- remaining fngers. In the previous 5 decades we have seen deinstitutionalization, community integration, self-d


AkaschaGambsette | 25-11-21 11:53
The month of Ramadan includes higher expression of devotion Suhur refers to the pre-daybreak meal at the start of the day’s quick along with fasting to be able to obtain nearness to and search and shall be referred to as “pre-daybreak meal” or “morning meal”. For ought to be paid to adjacent joint positioning to maximise instance, 20° of abduction on the proper hip joint results in a stretch or strengthening train. This diet has additionally been effective within the treatment of childish spasms and Lennox-Gastaut syndrome medicine 014 <a href=https://cemalta.gov.mt/education/aceclofenac/>purchase 100mg aceclofenac</a>.
Other notable modifications embody the addisections, immunohistochemical expression of lineagetion of mind invasion as a criterion for atypical meningioma associated proteins and ultrastructural characterization. Individual valuations of well being, psychological, and emotional well-being are generally summed across consultant samples of a population or country to estimate correspondences between life satisfaction and exhausting indicators of residing standards such as income, life expectancy, academic attainment, and environmental high quality. The effectiveness of neutrons as therapy of selection in the remedy of salivary gland tumors was most recently confirmed by Stannard et al heart attack 64 lyrics <a href=https://cemalta.gov.mt/education/telmisartan/>safe 20mg telmisartan</a>. Moxifloxacin could be taken with meals, but do not take milk-bas


Irhabarteepito | 10-11-21 21:53
Interna- Hematology Am Soc Hematol Educ Program 2011: tional recommendations on the prognosis and treat- 391пїЅ6. Patients should also perceive mucous mobilization and indicators and signs of asthma uncontrolled which may lead to an acute asthma attack. There are several reasons for this, including lack of awareness, a protracted latency interval, and nonspecific symptoms ulcerative colitis arthritis diet <a href=http://narpoly.gov.bd/practice/buy-naproxen-online/>buy cheap naproxen 250 mg online</a>.
If high-level evidence is missing, recommendations are revisions to the algorithms, which have been included into this primarily based on the panelпїЅs review of decrease-stage evidence and professional opinion. Note: The illness is well missed in Tanzanian settings as a result of lack of diagnostic services and should due to this fact be suspected in patients not responding to antibiotics/different therapy. In addition, laparoscopic and robotic-assisted surgical methods are additionally broadly used, although proof of their superiority to open prostatectomy is lacking gastritis with duodenitis <a href=http://narpoly.gov.bd/practice/order-lansoprazole-no-rx/>safe 15 mg lansoprazole</a>. Heavily encapsulated yeast (~5-10um in diameter) Aspergillus Fumigatus Causes a fungus ball cavity within the lungs. Normal erythropoiesis is characterised by the following progressive modifications: (a) Reduction in cell measurement (b) Maturing of the cytoplasm: because the cytoplasm steadily


UgrasalElivy | 05-11-21 22:50
Dotted lines on maps symbolize approximate border strains for which there could not but be full agreement. Patrick challenged his shlemiel mentality nearby asking himself the questions in Worksheet 18-7 with the Jack and Susan situation. These comprise: a summary of key findings, sections on methodology and evaluation, and summaries of the findings arising from the qualitative research and quantitative survey allergy vaccine uk <a href=https://mararosa.go.gov.br/documentation/purchase-cheap-zyrtec/>buy 10 mg zyrtec with amex</a>.
If future with simply eradicating one-half of the cattle from the dairy techniques and their administration usually are not social- system. Do not shake or in any other case deal with soiled linen and laundry in a way that might create a possibility for disease transmission or contamination of the surroundings. Hysteroscopic administration of residual trophoblastic tissue and reproductive end result: a pilot research symptoms bowel obstruction <a href=https://mararosa.go.gov.br/documentation/buy-online-secnidazole-cheap-no-rx/>purchase 500 mg secnidazole fast delivery</a>. The disease additionally locations a heavy economic burden on already restricted well being care sources within the Caribbean. The child's father retained the minor in Portugal and knowledgeable the mom by telephone. John wort (members of the Umbelliferae or the Rothmund-Tomson syndrome, Werner syndrome, and Apiaceae household) erectile dysfunction 31 years old <a href=https://ma

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