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

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

Афоризм
Любовь, которая никогда не бывает взаимной. Любовь к Родине.
 
Поиск


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

Triincefact | 06-04-22 07:21
noclegi pracownicze nieopodal suwalk <a href="https://www.pokojeiaugustow.online">www.pokojeiaugustow.online</a>
stx21


FordNeods | 03-04-22 08:44
The improvement of the guidelines was carried out underneath the auspices of the Division of Non-communicable Diseases. Considerations this affected person has diffuse atherosclerotic vascular disease, including coronary artery illness, carotid illness, and peripheral vascular illness. In exams done on laboratory animals, researchers repeatedly stimulate the In brainпїЅs temporal lobe exams carried out on with electricity over a laboratory animals, the period of many days heart attack young man <a href=https://www.buc.edu.eg/medpractice/calan/>order calan 240 mg visa</a>.
Relative to their much less happy of пїЅJim,пїЅ college students who had comparatively greater optimistic have an effect on have been friends, joyful individuals also report having stronger social assist extra likely to agree with optimistic inferences from the narrative (Matikka & Ojanen, in press), attending club conferences more fre. Figure 6 depicts our current information about lineage relationships of hepatocytes throughout embryogenesis and adult life. These changes would in the end be associated to growth of insulin resistance, liver steatosis and decline in muscle perform by way of train intolerance, amongst other vital consequences erectile dysfunction treatment brisbane <a href=https://www.buc.edu.eg/medpractice/cialis-black/>purchase cialis black in india</a>. Mice had been divided into totally different experimental groups at random when tumors reached a particular dimension. Overlap of refux


KapotthDrige | 25-03-22 12:50
Try Choose whole grain merchandise everytime you fruit that is ready to eat like apples, bananas can. In addition a supervisory institution that may help if any problems arise, ought to be named (for example the Director of a analysis division). If in your arms and feet but need the quantity of lean muscle mass to stroll, you would take some lost has been very vital, it’s strolling poles or go together with a pal venice arrhythmia 2013 <a href=https://www.aislesociety.com/mdocs/micardis/>20 mg micardis with visa</a>.
One who witnessed them says: Her changes would hardly waken a sleeping youngster. Patients with cardiac dis- Marked limitation of strange Patient can perform to com- Moderately compromised. There is proof that in World War I, German agents inoculated horses and cattle with anthrax and glanders at the Port of Baltimore before the animals have been shipped to France skin care for rosacea <a href=https://www.aislesociety.com/mdocs/benzoyl/>cheap 20 gr benzoyl otc</a>. For instance, there may be the hazard of labelling someone 'hypertensive' although the only problem is the affected person's use of a decongestant on the time. If it appears that the pri- Te habits of a tumor is the best way it acts within the mary website is not lymph nodes, unknown major body. Lingering high resting pulse pressures can degrade the centre, wisdom, and kidneys, and justification medical treatment erectile dysfunction code red 7 <a href=https://www.aislesociety.com/mdocs/vimax/>disc


Randallinantee | 18-03-22 07:32
Most of the patients who current for remedy even have tonic-clonic seizures and many have absence seizures. Lowering the dose of the drug, and B- classic pemphigus, cicatricial pemphigoid, bullous complicated vitamin administration. Two kinds of notices are required, those that should be given before the move, referred to as pre-transfer notices, and those that may be given within a short period of time after the move, referred to as post-move notices hypogonadism erectile dysfunction and type 2 diabetes mellitus <a href=http://www.mycenae-excavations.org/network/buy-cheap-vimax/>order 30 caps vimax mastercard</a>.
As Ahr activation is usually thought of necessary, however not suffcient, to induce ad- verse biological responses, and the doseпїЅresponse relationship for Ahr activation is generally quite steep, the relevance of excessive-dose rodent research corresponding to these to human пїЅlow-dose exposuresпїЅ isn't always clear. An abstract published in 2000 described the outcomes of a research involving 34 pregnant girls treated with protease inhibitors (none with amprenavir) compared with forty one controls that evaluated the affiliation with diabetes (four). Ricin can be prepared in liquid or crystalline form, or it may be lyophilized to make a dry powder cholesterol levels by age chart <a href=http://www.mycenae-excavations.org/network/order-online-atorlip-20/>atorlip-20 20 mg lowest price</a>. Systemic options are granulomatous synovitis, corticosteroid-responsivehe


SigmorRiskesk | 15-03-22 14:14
First, many candidate exams derive from about ocular surface cells and the meibomian gland and studies that had been subject to numerous types of bias (Table duct standing. Which of the next statements is true about when bariatric surgery should be considered. Global Journals accepts articles and manuscripts in each main language, be it Spanish, Chinese, Japanese, Portuguese, Russian, French, German, Dutch, Italian, Greek, or any other national language, however the title, subtitle, and summary ought to be in English gas treatment <a href=https://lincoln.edu.ng/prt/buy-online-lamotrigine-no-rx/>trusted 25mg lamotrigine</a>.
Finding a Foundation, and the Professional Beauty Association that helps experience to treatment shouldn t be. It is attributable to a Bowen’s Disease variety of microorganisms corresponding to staphylococci, Bowen’s illness is positioned on the shaft of the penis and the streptococci, coliform bacilli and gonococci. Sometimes it isn't completely clear which statistical analyses have been used, the values for p orfi usually are not reported, or no statements are made relating to the statistical signifcance of the reported relationships lidocaine arrhythmia <a href=https://lincoln.edu.ng/prt/order-cheap-olmesartan-online/>order 40mg olmesartan free shipping</a>. The time period “extreme” is usually used to explain the depth (severity) of a particular event. Unfortunately, issues from continual administration embrace steroid resistance, dependency


HectorExcatty | 15-03-22 12:12
Ascites could be distinguished from weight problems, as the onset of symptoms in ascites is quick, whereas obesity develops from a interval of months to years (Simel et al. Nevertheless, a classification have to be attempted, and that introduced right here is put forward in the hope that it will at least be acceptable, since it's the result of widespread consultation. Reported current cigarette use was greater among white non-Hispanic females (19 %) than amongst both Hispanic females (15 p.c) and black non-Hispanic females (7 p.c) muscle relaxant whole foods <a href=https://coop.gandaki.gov.np/explore/purchase-online-urispas-cheap/>urispas 200mg line</a>.
O bservationalstudies oflactose intolerance ormalabsorptioninassociationwith patientoutcomes (continued) Study Subjects Diagnosis and C ontrolforB ias C om m ents Excluded: Exclusion of fractures associated maturity (36–65 years), and later serving/day (high intake) throughout with extreme trauma did not have an effect on the outcomes maturity (> 65 years). Common options of apps embody the flexibility to track blood glucose, HbA1c, medications, physical exercise, and weight. His past medical historical past includes coronary artery disease, hypertension, and dyslipidemia erectile dysfunction 5gs <a href=https://coop.gandaki.gov.np/explore/purchase-viagra-professional-online/>buy cheap viagra professional 50mg line</a>. Durability of Response For six of the seven trials, the first endpoint was assessed at 26 weeks (i. In


RussellGah | 13-03-22 06:18
see here now https://howhealth.space/slovakia/joints-categ/name-shark-motion/


Iljaerrocculk | 09-03-22 11:53
Quantitative publish-mortem research of Opisthorchis viverrini in man in north-east Thailand. To avoid kids’s and younger folks’s difficulty in remembering actions, which is essentially because of the exercise sample being irregular and extra play-oriented, goal assess ment instruments are recommended such as step-counters or accelerometers. Lysosomal Storage Diseases Linked to Defects in Specific Enzymes Gaucher illness is the most common lysosomal storage illness (31) spasms spinal cord injury <a href=https://teachingselfgovernment.com/information/purchase-online-baclofen/>buy 10 mg baclofen mastercard</a>.
Studies have discovered no benet from antioxidant supplements, nutritional vitamins C and E, beta-carotene, and selenium. Identifcation of the cytochrome P450 enzymes involved within the N-oxidation of voriconazole. The questions on the subsequent web page can be used to information the conversation and assist patients make an informed choice women's health fresh pond <a href=https://teachingselfgovernment.com/information/purchase-clomiphene-online-in-usa/>cheap clomiphene 100mg line</a>. The laboratory can enhance biology laboratory to find out if their reference laboratory or the sensitivity of those strategies by employing numerous conother entity ofers the specified testing. There are two aspects of the medical standards relating to cardiac conditions and pilots. To avoid any liver trauma, compressions should not be utilized over the decrease third of the toddl


Farmongluts | 05-02-22 15:42
Safety and efficacy of a single-rod etonogestrel implant (Implanon): results from 11 medical trials. Coombs-optimistic autoimmune hemolytic anemia could happen in systemic lupus erythematosus and infrequently in other connective tissue ailments. Usually, they start treatment with chemotherapy, which is usually given within the hospital fungus synonym <a href=https://www.eldorado.ms.gov.br/journal/order-cheap-sporanox-no-rx/>buy sporanox 100mg with amex</a>.
Bronchodilators /Antiasthmatics Management of Asthma Asthma is a persistent inflammatory disease by which the patient suffers episodes of reversible airways obstruction due to bronchial hyperresponsiveness; in a couple of patients, irritation might lead to irreversible obstruction. In the clinic, however, the event of those antibody medication has been hampered by dose-limiting toxicities which have limited their utility and prevented approval of any co-stimulatory receptor targeting agonist antibodies. This analysis can then be and prevent a constructive feedback loop between ache and used to make further assumptions about the affected person’s stress reactions, for example, by intentionally creatpain triggers and maintenance situations, adopted by ing a positive a?ective state food allergy testing new zealand <a href=https://www.eldorado.ms.gov.br/journal/order-cheap-promethazine-no-rx/>purchase 25mg promethazine with visa</a>. The problems could be attributable to the conditioning remedy (the pre-transplant chemothe


Redgesuelieddy | 31-01-22 19:43
Diabetes mellitus in being pregnant primarily specifc genetically defned forms of diabetes or Patients with any form of diabetes may require insulin therapy at some stage diabetes related to other diseases or drugs. When a hint essentialness of others like cadmium, lead, tin, lithium factor is deficient, a characteristic syndrome is pro- and vanadium is weak (Albion Research Notes, 1996). Ostomies can be either momentary or everlasting and are performed for a number of etiologies similar to, however not limited to: colorectal cancer (36%); inflammatory bowel disease (15%); bladder cancer (12%); diverticulitis (11%); necrotizing enterocolitis, congenital anomalies, HirschsprungпїЅs disease and other cancers and conditions such as obstruction, perforation and trauma (The Oryx Group, 2001) whole woman's health <a href=https://sja.pi.gov.br/catalog/order-capecitabine-online-no-rx/>buy cheap capecitabine 500 mg on line</a>.
Co-existing ischaemic heart disease is a big cause of peri-operative morbidity and mortality in sufferers undergoing carotid endarterectomy. The commonest medical manifestation is stomach ache, typically very intense, with or without eosinophilia. Chest radiographs often show decrease and/or expectorated sputum, induced sputum or early center-lobe infltrates, typically miliary and sometimes morning gastric aspirates should be carried out every time without cavitation erectile dysfunction young age <a href=https://sja.pi.gov.br/catalog/order-cheap-tadala-black

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