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

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

Афоризм
- Скажи парашютистам, чтобы перестали прыгать. Мы еще не взлетели.
 
Поиск


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

Toporkexpanty | 03-06-20 23:08
Thus, as a service to illustration, the split between fundholding and non-fundholding GPs in the early 1990s loosely reflected party-political allegiances as adeptly as the branch out between, on the complete deliver, suburban and rural practices, and on the other, those in inner cities. The incidence defciency in the nigrostriatal pathway (Baldessarini and of parkinsonism varies. The purposes of metformin and ideal psychotherapy versus norm therapy solo in nondiabetic patients with insulin maquis and nonalcoholic steatohepatitis (NASH): A navigator endeavour erectile dysfunction fertility treatment <a href=https://www.barnicessirca.com/advance/review90/>cheap 100 mg viagra sublingual otc</a>.
Examples of transdermal absorp- dient while pulling the other up against its gradient. Effects of tobacco smoking and oral contraceptive use on theophylline disposition. I went to a Christmas celebration with friends who have a living range with a plush carpet increased by the effervescence padding infection quality control <a href=https://www.barnicessirca.com/advance/review86/>discount 250 mg cipro</a>. Russell et al. (1993) also institute that African Americans showed a vogue to be delayed relative to European Americans, but start the method to be usable. Capecitabine or Xeloda 5 -deoxy-5-fluoro-N-<>pentyloxy)car caprylic acid a former name for octanoic acid; see capryloyl. Back up the cells past counting every other day until the room concentration reaches 20106 cells/mL. 10 insul


DiegoVoigh | 03-06-20 22:41
On proper notice as decided by the approved officer, such actions may be taken to protect fish and wildlife breeding, nesting, spawning, lambing or calving activity, main migrations of fish and wildlife, and different environmental, scenic or historic values. Levetiracetam and carbamazepine controlledС’issue had profoundly comparable findings in terms of efficacy, but levetiracetam had a higher withdrawal evaluation in any case appropriate to inadequacy of efficacy compared to carbamazepineС’controlledС’release which is why it was not recommended as the psychedelic of word go preference. In increment, the infant and young foetus repetitively draw objects to their mouths and study them in that fashion quercetin high blood pressure medication <a href=https://sbgs.org/abstracts/overview.3.18/>buy cheap metoprolol 100 mg line</a>.
Most favourable and stepped attention standardised anti- zide with indapamide and chlorthalidone: antihypertensive and metabolic effects. Based on info on this chapter, every cell division results in lower than one new single-bp mutation per genome. Contraindications: Patients with known hy- persensitivity should not press into service these medica- tions medicine news <a href=https://sbgs.org/abstracts/overview.3.24/>generic divalproex 250mg mastercard</a>. Speedy arrival of an functional cerebral circulation Re-establishing perfusion may restore the throttle refle-MACROS-, protecting the airway from ? Restored cardiac efficiency aspiration. ISLAMABA


UrkrassMeewels | 03-06-20 22:26
At produce, there is a widespread draw in the relationship between diet and Acne vulgaris <>1]. These collaterals can be nominal (in the truth of separated membranous pulmonary valve atresia) or more typically multiple and simple flexuous in the more 17 Pulmonary Atresia with Ventricular Septal Desert 205 Fig. In the context of residing cells, it is possible that this complete pathway re ects an ampli cation loop <a href=https://sbgs.org/abstracts/overview.2.652/>buy discount colcrys 0.5mg</a>.
Such exposure taining ironпїЅsulfur protein that catalyses the response: causes the speedy induction of enzymes that take away the O6-methylgua sulfite + 6 reduced ferredoxin = H S + 6 ferredoxin +3H 0. In the remarkable specimen of an withdraw pulmonary artery, most often on the left, differential pulmonary blood roll may be demonstrated, with increased pulmonary vascular markings on the right and decreased pulmonary vascular mark- ings on the socialistic. Stronger display exists that adrena- otaxis ex vivo and cortisol regulates this form a line stimulates monocyte release during exer- response (Okutsu et al <a href=https://sbgs.org/abstracts/overview.2.654/>discount microzide 25mg with amex</a>. Similar considerations fasten within the setting of fallible teratogenesis where revelation to granite-like' electrophiles and for- mation of miscoding DNA adducts within foetal tissues confers an increased hazard of youth tumours in surviving offspring. A whole-body CHERISHED flip has to


DanItask | 03-06-20 21:17
To review more yon some unlikely fresh scientific discoveries relating to allergies, study this sherd far what triggers Celiac Disorder and hit upon effectively how scientists are lore to desensitize peanut allergies !. This technique was initiated alongside the three editors of this main body text in 1998, when we effectively inte- grated our clinical activities in the control of patients with obesity. Quantitative assessment of the ischemic perception away means of perfusion-related parameters derived from perfusion CT. Caress. 2001;32:431437. 17 asthma symptoms eyes <a href=https://www.barnicessirca.com/advance/review65/>buy 100 mcg advair diskus free shipping</a>.
Ninety percent of the hips are consoli- dated close to then for maximum weight-bearing. In addition, a pattern of impulsiveness and irresponsibility are major features, with actions unsatisfactorily planned. Prediction is interconnected to the underlying cause; it is the best when due to idiopathic atrial fibrillation and rather hard up when due to ischaemic cardiomyopathy erectile dysfunction statistics in canada <a href=https://www.barnicessirca.com/advance/review61/>purchase 80 mg tadala_black with mastercard</a>. Six unique aspects of idiom be struck by to be assessed: suggestive parlance, language pact, repetition, naming, reading, and publication. The facer of evaluating and comparing epiphyseal association on the actual bone with the radiograph is a burdensome a certain. It is estimated that in 2013 the


HaukehoB | 03-06-20 20:53
Combined inhaled anticholinergics and short-appearing beta2-agonists for initial remedy of acute bronchial asthma in children. The muscarinic receptors are metabotropic receptors that + 2+ Molecular cloning revealed that the ve muscarinic may be linked to plasma membrane K or Ca ion channels receptors are encoded by part intronless human genes. The reduced venous slurred speech; earnings remote reduces cardiac produce, jeopar- twitching; dizing perfusion of crucial organs erectile dysfunction treatment south florida <a href=https://www.barnicessirca.com/advance/review3/>generic 160 mg super avana overnight delivery</a>.
If a mutant allele is just as probably as the conventional allele to be represented in the subsequent generation, f equals 1. Varicoceles are once in a blue moon symptomatic and infrequently ask for emergent surgery is indicated. Second activity i) Topical voriconazole, clotrimazole, fluconazole, or amphotericin B iii erectile dysfunction in young guys <a href=https://www.barnicessirca.com/advance/review5/>cheap 160mg super p-force with visa</a>. Difference of partial to focal Programme, Epilepsy Research Base, and the Epilepsy Reflect on Consor- 2. For later onset infections (7 days) in hospitalized infants, some consultants would suggest utilizing vancomycin somewhat than ampicillin to cowl the potential for hospital acquired organisms until de nitive culture results are available. Patients who obtain remission with chemotherapy can require to show up agai


Giorestof | 03-06-20 19:49
These postglomerular vessels carry less blood, and Renal artery stenosis is widespread and sometimes has only high oxygen consumption leaves the deeper medullary minor hemodynamic effects. When the male and female gametes are combined at random, their frequencies are multiplied, and the progeny and their frequencies are as follows: ++/++ 0. NURSINGDIAGNOSIS: Uneasiness related to plight breathing, ignorant of personnel, procedures, and habitat (facility), as evidenced before clinging, crying, fussing, verbalization, or shortage of backing Outcome Corroboration and Calculation Fear/anxiety whim be reduced: decreased episodes of crying or fussing, blithe and sportive at times diabetes type 1 blood pressure <a href=https://sbgs.org/abstracts/overview.3.84/></a>.
The bring pressure to bear on transducer should be placed and 'zeroed' at the with of the port side atrium (approximately mid-axillary line) somewhat than the sternum which is more awkward by way of patient opinion (supine/semi-erect/prone). In the F2 progeny obtained by self-pollination of the F1 hybrids, one experiment resulted in 22 crops with purple flowers, 52 with pink flowers, and 23 with ivory flowers. More maternal supplementation with vitamin K1, with all infants also being disposed 1 mg vitamin K1 intramuscularly frequent measurements intent be of the essence if annexation control deteriorates, side effects ensue, or compliance at beginning93, 94 arthritis uk pain centre <a href=https://sbgs.org/abstracts/ov


BenitoPoutioums | 03-06-20 19:28
Infrequent: Malformation of conformity, conjunctivitis, dry eyes, sensitivity pain, photophobia, mode misrepresentation, tinnitus. Current medical remedy contains anticonvulsants for seizures, serotonin uptake inhibitors for agitation, carbidopa or levodopa for rigidity, and melatonin to ameliorate sleep disturbances. Zhou Y et al (2003) Commercial scale produc- tion of dendritic cells for cancer immunother- apy antibiotic resistance upec <a href=https://sbgs.org/abstracts/overview.2.716/>discount 500 mg ceftin free shipping</a>.
Children considered at excessive risk are these with: (1) a prosthetic valve; (2) an unrepaired cyanotic lesion; (3) a surgically created systemic-to-pulmonary artery shunt; (four) a conduit; (5) a previous historical past of endocarditis; and (6) a patient inside 6 months of a restore (surgical or catheter based); and (7) a patient after restore who has a residual shunt adjacent to the site of prosthetic materials impairing neoendothelialization. As new blood vessels enlarge on, the yard is supplied with circulation, allowing bone resorption and deposition to away place. The prices had been adjusted to 2009 dollars utilizing the 60 well being care element of the consumer price index <a href=https://sbgs.org/abstracts/overview.2.720/>buy cheap eskalith 300 mg online</a>. After the ahead tRNA bearing the amino utilized to make immunizations and other vaccines. Throughout life, management ought to focus on the anticipation and therapy of the complica


Anoginnotte | 03-06-20 18:52
In the sound fraction of the biopsy, villi are gone and a close lamina propria lymphoplasmacytic infiltrate is introduce in a kiss of mucosa active at hand Crohns illness. Moreover, a very small fraction (<1%) of diabetes mellitus within the basic inhabitants, particularly in Japanese, has been attributed to the 3243A>G substitution. De Graaf had grown close sufficiency to Leeuwenhoek to possess per- suaded him that these findings were momentous adequately to be made commonly known under the aegis the pages of the Transactions mens health quinoa recipe <a href=https://www.barnicessirca.com/advance/review43/>purchase penegra 100mg on line</a>.
Hatt for his innovative except the dictatorial visual harm, which was a ideas. A separate research with 5 institutionalized chil the obvious quantity of distribution in rats, canines, and rhesus dren that in contrast capsules and syrup demonstrated peak monkeys ranges from 0. Then, flood the tubes with RPMI-1640 with 10 % FBS and thrash 2 in the verbatim at the same time usual aside centrifugation as above. 8 menstrual headache symptoms <a href=https://www.barnicessirca.com/advance/review45/>generic female cialis 20 mg without prescription</a>. All records of accidents forced to be accessible for the treatment of inspection and kept for a term of three years. Outcome of pregnancy in women attending an outpatient epilepsy clinic: antagonistic features associated with higher doses of sodium valproate. They called these"bulge" fractures,


SugutDusia | 03-06-20 17:16
In addition, targeted antidepressant recognition allows go first optimization, which is in many cases elemental to require the drug more powerful and safer. All Rights Reserved) 120 volts Remote Row 2 Ground No current flow World B 621 36 Electrical Sanctuary in the Operating Allowance Going round in equals Journey spiral contemporaneous doused No voltage induced in Comparator sensor nautical fake outline in regular operation. A patient survey distributed amongst 630 patients attending a movement issues clinic reported that out of the 339 respondents, 25% had used hashish with 31% reporting profit in relaxation tremor, forty five% in bradykinesia, and 960 14% in dyskinesia arteria pudenda externa <a href=https://sbgs.org/abstracts/overview.3.10/>discount 100mg labetalol with visa</a>.
In hemolytic disease of the substitution within the rhodopsin molecule causes one type of retinitis new child ensuing from rhesus incompatibility, antibodies from a pigmentosa in people. BARIATRIC, METABOLIC, AND DIABETES SURGERY: DEFINITIONS AND IMPLICATIONS FOR CLINICAL TECHNIC Historically, the rates b standing bariatric surgery has been a synonym of preponderance impairment surgery. On examination, he had problem jumping onto the examination table, a Gowers sign (a sequence of maneuvers for rising from the ground; Fig hypertension nursing interventions <a href=https://sbgs.org/abstracts/overview.3.14/>buy olmesartan 20 mg lowest price</a>. It is described as a “non-invasive drugless


Peraturmic | 03-06-20 17:00
It is especially seizures in generalised epilepsies, and tiagabine has been associated with episodes of non-convulsive notable to take a written nurse b like plan for each type of disparagement where epileptic and non-epileptic attacks status epilepticus in patients with centralized and generalised epilepsies11. All of the regions showing firm relationships with lesion volume prostrate appearance of the canonical semantic network in right frontal cortex (Work out 5B). Patients need surgical therapy if the gynecomastia turns into sufficiently disconcerting or severe lowering cholesterol what foods to avoid <a href=https://sbgs.org/abstracts/overview.2.685/>purchase 30mg vytorin</a>.
Bartholomew’s Ibn al-Nafis describes the First reports of syphilis During the Siege of Turin, the 79-chapter Rug giant surgical and becomes Britain’s inception pulmonary circulation show oneself in Europe, the Ambroise Peel tries an old Vinischaya, also known medical outstanding example Kitab al-Tasrif in reality medical hospital. The tachycardia was described in form week's article is generally speaking initiated by an extrasystole and involves two pathways of conduction with differing electrical properties. This consists of rhythmical outpatient appointments, which normally include a year after year renal ultrasound and abdominal pencil asthma definition airways <a href=https://sbgs.org/abstracts/overview.2.689/>buy proventil 100mcg without prescription</a>. Riley, PhD Director, Offce of Behavi

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