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

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

Афоризм
Опьянение победой подчас переходит в алкоголизм.
 
Поиск


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



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

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


UrkrassStoma | 27-10-21 22:27
Tese tumors are found exterior the marrow, may happen beneath the pores and skin or other locations, and will be the frst sign of leukemia. The improvement of diminished symptomatic awareness of hypoglycaemia also reduces the identification of episodes by the affected affected person, and generally signs are attributed to hypoglycaemia when the blood sugar is not in fact low. Associated Features: Fear and different features of increased autonomic exercise, similar to tachycardia, can occur diabetes mellitus y enfermedad periodontal <a href=https://db.berkeley.edu/wp-content/clinical/glyburide/>purchase genuine glyburide on-line</a>.
Pseudoexfoliation syndrome - usually at pupil border and speckled defects all through iris 3. People with stomach cancer normally obtain external-beam radiation remedy, which is radiation given from a machine exterior the body. When the eyes become inflamed, they turn out to be very sensitive to gentle and the patient feels confounded, but in Conium even if there isn't any swelling or irritation of the attention, the sensitivity to gentle remains to be increased and the eyes water prehypertension eyes <a href=https://db.berkeley.edu/wp-content/clinical/lanoxin/>order 0.25 mg lanoxin with amex</a>. The microbiology of the illness has changed considerably because the introduction of the Haemophilus influenzae type B vaccine within the 1980s. A dysfunction in which brief intense periods of vertigo, typically accompanied by nausea, are provoked by m


Dimitarblurb | 20-10-21 01:36
Identification of such genetic variants in people patients would permit for extra individualized, rationally-designed, and ultimately, more profitable drug remedies. Active and inactive Amprenavir is metabolized in the liver to energetic and inactive metabolites and is minimally excreted in urine and stool. Data must be recorded in a 256 256 matrix into a pc for subsequent analysis sleep aid vitamin melatonin <a href=https://www.manorongoldenpond.com/explore/buy-sominex-online-in-usa/>order generic sominex canada</a>.
It is nevertheless doubtless that there's appreciable uncertainty around the disease stage particular hazard ratios, and this has not been explored by the company in sensitivity evaluation. Laurie I 39 m undecided after I implanted however I guess it was late as I didn 39 t get bfp till 13dpo and even then it was a really very faint line on a 10miu check. Small bowel obstruction following radical hysterectomy: risk nationwide burden to outline operative emergency basic surgical procedure allergy symptoms lilies <a href=https://www.manorongoldenpond.com/explore/order-loratadine-online-no-rx/>generic loratadine 10mg mastercard</a>. For the epidemiologist, the vidual with a single unprovoked seizure or with two or extra problem is correct diagnostic information to distinguish unprovoked seizures inside a 24-hour interval is often not well-characterized forms of epilepsy from neonatal seizures at that time thought-about to have met the criteria for labeling which


DargothRix | 12-10-21 00:54
The key points for logistics planning embrace utilizing the identical format for micro?planning in any respect levels, making easy and consistent calculations and ensuring adequate cold space at all ranges. Describe drawbacks related to the use which are available as encapsulated granules of topical powder dosage varieties and provide that when opened may be added to food or examples of different dosage types that may drink prior to administration. A2820 the information contained on this program is up to date as of March 9, 2017 <a href=https://blog.scottevest.com/medprograms/order-online-mesalamine-cheap-no-rx/> medications ok to take while breastfeeding order genuine mesalamine online</a>.
In the earliest vertebrate species, the cerebrum was not much more than olfactory bulbs that received peripheral low-down hither the chemical environment (to right it smell in these organisms is indistinct because they lived in the the depths). Often a single drug, which is usually If something, these research result in the conclusion that solely a very efficient within the first years, is constantly used till it no very substantial discount in susceptibility could be detected longer works. When using the exercise with a couple where one partner has AspergerпїЅs syndrome, I ask the typical partner to elucidate his or her love for the partner with AspergerпїЅs syndrome, and what the enchantment was after they first met <a href=https://blog.scottevest.com/medprograms/order-prandin-online-


Copperpibiaplug | 10-10-21 23:05
For instance, an acute otitis media will end in low compliance indicating a stiff tympanic membrane as a result of the area behind the tympanic membrane is full of fluid. Safety gear additionally might include objects for personal safety, similar to gloves, coats, gowns, shoe covers, boots, respirators, face shields, security glasses, or goggles. A examine from Alberta confirmed that the number of hospital admissions for hepatitis C-associated illness is increasing (1) <a href=https://blog.scottevest.com/medprograms/buy-cheap-amantadine-no-rx/> hiv infection symptoms how soon buy 100 mg amantadine visa</a>.
Ewing sarcoma might recur in the type of distant disease as long as 15 years after the initial diagnosis. Another way to operationalize low frequency could be the definition used for orphan illnesses, i. The most typical etiologic agents of period, corresponding to 2 hours, it is anticipated that the pattern should tradition-negative endocarditis, Bartonella spp and Coxiella burbe refrigerated afer that point except specifed otherwise in that netii, ofen could be detected by conventional serologic testing <a href=https://blog.scottevest.com/medprograms/buy-cheap-trandate/> - arrhythmia discount trandate 100 mg otc</a>. Enteral feedings could also be started concurrently if the toddler is otherwise steady and fluid overload is not a concern. The duplications and deficiencies are the same as partly A, however on this case both products are monocentrics. In cattle breeding


Finleyprielffed | 04-10-21 07:16
To assist check this speculation, eleven kids with regressive-onset autism had been recruited for an intervention trial using a minimally absorbed oral antibiotic. If there may be any discrepancy, stop the transfusion immediately and consult the blood financial institution. In many developing nations, biomass smoke publicity A body of literature now helps an affiliation between happens throughout the whole life span <a href=https://www.dominicanrepublic.com/publications/purchase-online-thorazine/> symptoms 1974 order cheap thorazine on-line</a>.
Next, they estimated that every woman may harvest sufficient roots to bring 5 kg of roots to a furnishings making workshop sponsored by the Association. Comparisons of demographic estimate the sensitivity and specifcity of the and baseline medical options of topics earlier than end result variable. A concentration of >103 cfu/mL urinary tract pathogens in the ejaculate is indicative of significant bacteriospermia <a href=https://www.dominicanrepublic.com/publications/purchase-desyrel/> anxiety tumblr discount 100mg desyrel otc</a>. Pancreatic most cancers might end result from hereditary germline or somatic acquired mutations in cancer-associated genes and mutations also cause most cancers progression and metastasis. Sequences are identifoed by GenBank accession number, geographic location, year of sample assortment, and virus genome type identifed. As both chloroquine and piperaquine have the cardiotoxicity of antimalarials | 9 ter


Grimbollartibia | 11-09-21 23:03
The same is true for estimates of the variety of Veterans in the United States in any specific fscal 12 months. Modeling and function-playing are basic strategies of conduct therapy which simply involve the interplay of patient and therapist and the affected person and important others as fashions for desired habits acquisition. Visualise the Cervix It could also be diffcult in some patients to visualise the cervix but each try needs to be made to get a transparent view of the transformation zone, external os and into the endocervical canal medications jokes <a href=https://ngen.com/education/practice55/article8/>order 500mg meldonium mastercard</a>.
Positive echo that does not meet major criteria Lab Diagnosis Diagnosis: Diagnosis confirmed by 2 major/1 main + Blood Culture 3 minor/all 5 minor standards. A2752 During Tracheal Intubation and In-Hospital Mortality Among Critically Ill Adults/B. Do not give steroids, Candidemia is turning into more and more widespread in mannitol or acetazolamide erectile dysfunction treatment in uae <a href=https://ngen.com/education/practice55/article7/>buy 100 mg viagra mastercard</a>. These agents are much less efficient in reducing blood glucose levels than metformin or sulfonylureas and cut back HbA1c by zero. Diagnostic analysis of hepatocellular carcinoma in groups and preventive methods. Various types of cellular responses to cell harm could also be Cell Membrane as follows qc arthritis pain relief <a href=https://ngen.com/education/

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