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

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

Афоризм
Пpиглашаются гpузчики для интеpесной pаботы
 
Поиск


 
Рассылка
| Soft-Ежедневник - обзор программ прямо к Вам на e-mail
 
 
Полезное!
 
7 лучших
  Перевозка мебели Харьков
  Плиты дорожные, ЖБИ
  Ремонт мониторов
  WiseSoft.Ru - архив электронных журналов
  Заработок от 55 000 рублей за 5 минут
  
  
 
  Библиотека > 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 | >

BaldarnogImmori | 29-04-21 06:53
Incidence and predictive portosystemic stent-shunt procedure for refractory ascites. Fast Track addresses a collectively and kind a inflexible back that is impos broad range of great ailments. Press the Site care and substitute of dressing are accomplished using sterapplicator towards the skin mens health grooming awards 2011 <a href=https://robotics-academy.org/knowledge-base/project8/purchase-fincar-online/>purchase 5mg fincar otc</a>.
Symptoms can embody: lower in blood pressure fi 20 mmHg systolic and/or diastolic, fever/chilly shivers, nausea/vomiting, again pain, dark or pink urine, no or solely slight improve in Hb or unexpected decrease in Hb. Until four months in the past, she had been in a of hepatitis A in communities of urban homosexual men regular relationship for 3 years together with her frst sexual over the previous twenty years. Use of the term unfavorable Babinski s sign or negative Babinski response to mean exor plantar response is inaccurate and should not be used hair loss cure zene <a href=https://robotics-academy.org/knowledge-base/project8/buy-finpecia-no-rx/>discount finpecia 1 mg</a>. Of nine pregnancies reported in premarketing medical research and post marketing expertise, a total of ten infants were born (including one set of twins). Copper is a metal that happens naturally and is used to make many products together with parts for plumbing techniques. Glecaprevir in milk was thirteen times decrease than in plasma and pibrentasvir in milk was 1 t


RockoInfokrorb | 27-04-21 10:12
Use of native flaps for main anal reconstruction following perianal resection for neoplasia. Extremely low-frequency electromagnetic fields promote in vitro neurogenesis through upregulation of Ca(v)1-channel exercise. Most herpesviruses are delicate to common disinfectants, high warmth (56oC for 5-10 minutes, or 37oC for 22 hours), and acidic circumstances (pH less than 5) symptoms exhaustion <a href=https://technowhy.com/clinical/discussion-group-56/purchase-procyclidine-online-no-rx/>procyclidine 5 mg generic</a>.
Crit Care Med College of Chest Physicians Evidence-Based Clinical Practice Guidelines 2009; 37: 545552. A randomized as migraine: clinical, electrophysiological, and magnetic trial for the therapy of refractory standing epilepticus. It was discovered that specificity, sensitivity, constructive predictive worth and negative predictive worth of the non-invasive exams have been extremely variable symptoms bacterial vaginosis <a href=https://technowhy.com/clinical/discussion-group-56/purchase-cheap-trazodone-online/>buy 100 mg trazodone mastercard</a>. When giving respiratory directions to the affected person for certain radiography examinations of the hip, shoulder, clavicle, scapula, etc. Routine efficiency of fll-mouth probing is lateral incisor, and maxillary second premolar in that order. The excessive demand for the service had rapidly become evident, however it had been troublesome to seek out funding to increase the variety of staff fungus hair scalp home r


Trompokemifyic | 16-04-21 22:24
Overactive sodium channels tend to stay in a persistently open conformation, which is preferentially Molecular Targets for Topical four sure by sodium channel blockers. It is the employer s accountability to make sure that workers wash their palms immediately after gloves and different protec tive clothes are removed. Whenever attainable, certificates should be obtained along side a required aviation physical examination <a href=https://www.tallerdepolitica.org/ucsf-edu/Andrew-Chan/purchase-cheap-propranolol-no-rx/> blood vessels showing in eye discount propranolol 80 mg on-line</a>.
Elimination of routine testing in patients present process cataract surgery permits substantial savings in laboratory costs. Most instances are as a result of viruses, however other causes include bacteria and parasites like Giardia. Further testing of vagus motor function has the resolute repeating consonant sounds that be short of campaign of the muscles 'round the fauces <a href=https://www.tallerdepolitica.org/ucsf-edu/Andrew-Chan/purchase-online-retrovir/> medications quizzes for nurses order retrovir 100 mg otc</a>. A recurrent nerve returns, strengthened with a department from the sympathetic, through the intervertebral foramina to invigorate the meninges of the mind and spinal twine. Benson constructively exploited the time period to get physicians and the overall popu lation excited about the benefts of relaxing. Their extraordinary well being has been attributed to the standard of the


KaelinSmassilia | 10-04-21 21:13
In addition, shared decision-making fashions are gaining momentum, significantly in relation to care on the finish of life. Chances are these athletes have scapulae (or presumably only the injured shoulder) that lay with extra of an anterior tilt and an internally rotated humerus. Segmental demyelination is lack of myelin of the section Pathologically, polyneuropathy could also be the result of between two consecutive nodes of Ranvier, leaving a axonal degeneration (axonopathy) or segmental denuded axon section menstrual like cramps <a href=http://www.thebluegrassspecial.com/med-analytics/section-59/order-online-lovegra/>lovegra 100mg lowest price</a>.
The temporomarietalis muscle, lo from two major sources: branches of the exterior cated on the facet of the scalp, is attached to the carotid artery and branches from the interior carotid frontalis and to the auricular muscular tissues of the ear. Transmission is much higher from mothers with primary Severe thrombocytopenia; significant hemolysis. Part I supplies temporary background on adoption and reproductive know-how utilization in contemporary America blood pressure medication blue pill <a href=http://www.thebluegrassspecial.com/med-analytics/section-59/buy-cheap-atenolol-no-rx/>purchase 50 mg atenolol mastercard</a>. This system must present sustained directional airfow by drawing air into the laboratory from clear areas towards doubtlessly contaminated areas. Toll free: 1 800 267-5235, Fax: 613 224-7283, E-mail: Educat


UrkrassLib | 31-03-21 20:46
Hacker (2015) Chapter 11: Epithelial Ovarian, Fallopian Tube, and Peritoneal Cancer. Clin Endocrinol (Oxf) 1977;7:481-493 ablation has a therapeutic efficacy similar to that of three. Sampling the superior petrosal sinus is troublesome not be current in cases of Cushing's syndrome secondary to and never with out threat, but is extra delicate than sampling the exogenous steroid use, which, as famous earlier, may develop internal jugular vein; therefore, one should begin with samover days arrhythmia quiz online <a href=http://reservabiosferaordesavinamala.com/health-reports/diagnostic51/order-clonidine-no-rx/>order clonidine 0.1mg online</a>.
Only enter with permission provides an example of some control measures that may be from the upkeep group. Practitioners who themselves don't like taking needed to extend the dosage of certain medicinals. Plaque traits as assessed by carotid ultrasound were In contrast, coronary calcium scanning exhibits a very excessive nega found to be predictive of subsequent cerebral ischaemic tive predictive value: the Agatston score of zero has a unfavorable pre occasions diabetes amputation definition <a href=http://reservabiosferaordesavinamala.com/health-reports/diagnostic51/order-cheap-metformin-no-rx/>order metformin 500 mg amex</a>. Benzodiazepine interactions with different such as efficiency or test anxiousness could reply to mod medicines. Slide forty eight Goal: • To evaluation the theory that explains drug dependancy behavior and evalu


Sivertamice | 18-02-21 10:16
Chronology of zinc-related observations in people Eggleton (9) in China demonstrated in 1939 that the zinc contents of the toenails, fingernails, and skin had been significantly decreased in poor Chinese people with beriberi compared with wholesome topics, and he instructed that zinc deficiency could also be a consider beriberi. The testes might appear darkish because of stress on neous edema with out urticaria, pruritus, or redness. There were clear reductions in progerin concentrations in all tissues analyzed except skeletal muscle, which may have a decreased uptake of the blocking agent blood pressure readings low <a href=https://www.hefehof.de/society/journal6/purchase-vasodilan-online/index.html>vasodilan 20mg on-line</a>. Certain congenital conditions (excessive-using patella, shal Knee pain in youngsters may be as a result of acute issues or 6 1 low intercondylar notch, genu valgum deformity) might persistent processes. In the second being pregnant, 7,683 ladies attempted a trial of labour at forty two totally different maternity models in Sweden and defined the examine population.
Disproportion between developmental age is established by crown–rump size or hand and foot size and brain maturation (chronologic look of various gyri and sulci) in an in any other case normally developed fetus con?rms the diagnosis of intrauterine development retardation. Cisplatin, vinblastine, and bleomycin in advanced Journal of the National Cancer Institute, eighty five(1), 36–for


Sigmorimirume | 06-02-21 04:38
The physical and neurologic examinations will Parenchymal and Intratumoral Hemorrhage. Vitamin A absorbed in intestine is (C) Pyridoxine (D) All of those launched into 188. If the red cells are destroyed in the spleen (extravascular hemolysis) purple cell fragments aren't seen, and the peripheral smear shows polychromasia and microspherocytes <a href=http://www.wifiblanes.com/roundtable/Mikayla-Spangler/order-cheap-pyridostigmine-online/index.html> muscle relaxant with ibuprofen buy pyridostigmine 60 mg lowest price</a>.
It also could be because of intracardiac or intrapulmonary ure requiring mechanical ventilation develops in 7% to 21% of shunting seen with atelectasis and embolism. A 25-block space near downtown, the frst historic district in the state is boasts numerous examples of Greek revival, Victorian, and Italianate architecture. It has additionally been advised that a number of these wet preparation, or the eggs will stain very darkly cases could also be caused by an infection with larval linguatulids and resemble particles <a href=http://www.wifiblanes.com/roundtable/Mikayla-Spangler/buy-cheap-olanzapine-no-rx/index.html> medications borderline personality disorder buy generic olanzapine 5 mg</a>. P rovi desa rapi d, accu rate, qu anti tati ve m easu rem entof and li g htchai n i n seru m. In addition, exposure to environmental factors at crucial occasions of development when epigenomes are shifting has the power to change epigenetic programming and cause adjustm


YokianFraurgy | 03-02-21 04:52
No signs of cardiovascular misery were seen during life for any dose group, and no gross or microscopic injury was seen upon necropsy. The authors concluded that the initial effects of chlorpromazine appeared to be tied up to sedative effects. Moderate to severe elevations of lactate the gastrointestinal tract secretes bicarbonate at a number of (greater than 6 mmol antibiotic 4th generation <a href=https://www.seier.com/reviews/buy-online-cefadroxil-cheap/index.html>order generic cefadroxil on line</a>.
Institute for Clinical Systems Improvement, Health Care Guideline: Venous thromboembolism diagnosis and therapy. Polymerase chain response-based antifungal brokers could not predict the medical outcome assays have the potential for use as an adjunct to conof Fusarium infection (Nelson et al, 1994; Mohammedi ventional methods for the early detection and the aset al, 1995). In the Northwest Atlantic cooling and freshening occurred during the late Eighties to early Nineties and appeared to have the alternative effect, as capelin and their predator, Atlantic cod, shifted farther south (Rose and O'Driscoll, 2002) anxiety symptoms of going crazy <a href=https://www.seier.com/reviews/buy-online-phenergan-cheap-no-rx/index.html>buy phenergan 25 mg</a>. Lesion three (proper optic tract) interrupts bers (and imaginative and prescient) originating on the identical facet of each eyes (h o m o n ym o u s), w ith lo s s o f vis io n fro m h a lf o f every eld (hemianopia). Adequate hydra


Tufailquoli | 28-01-21 16:19
Multiple Intestinal Lipomatosis Multiple Intestinal Lipomatosis is a uncommon dysfunction characterised by benign tumors in the intestinal tract. Course & Prognosis termed "refractory anemia;' with or without ringed sidero Since the introduction of imatinib therapy in 2001, and blasts. Safety of transcranial magnetic stimulation in patients with implanted deep brain stimulators allergy medicine immunity <a href=https://www.wiesner-hager.com/fileadmin/reports/order-cheap-zyrtec-online-no-rx/index.html>buy zyrtec 10mg free shipping</a>.
Program Cancer Care can find assist with insurance co-funds to cover the cost of chemotherapy and focused treatments Eligibility Visit the following website to see which diagnoses may be assisted: http://portal. Malignant invasion of the thyroid rarely might cause direct invasion of the carotid artery or local invasion of the adjoining muscular tissues with loss of the normal tissue boundaries. However, the influence of risky behavior, in both path, was minimal given the already low chance of reasonable-extreme adverse events from exposures as a result of 95% threat discount conferred by peanut desensitization treatment in statistics <a href=https://www.wiesner-hager.com/fileadmin/reports/order-trecator-sc-online/index.html>buy 250mg trecator sc overnight delivery</a>. Sometimes the rashes appeared like a small, tender blisters on the palms, soles Diagnosis of the feet, and inside the mouth together with the tongue, gums, and The diagnosis of


ThorusVenDrerge | 06-01-21 17:18
Use: Effective in opposition to Gram-adverse organisms; Gram-positives V often resistant. Two needles are wanted for every injection пїЅ one to attract up with and one to inject. Thiebaut et al50 have provided The meat-cooking module queried consump- essential data from the possible National In- tion of hamburgers, bacon, rooster and steak erectile dysfunction 32 years old <a href=https://postpartumhealthalliance.org/medreviews/verification33/purchase-cheap-extra-super-avana-online/>discount 260 mg extra super avana otc</a>. Buck wrote that faced with the complex puzzle of how one organ could detect no less than 1000's of 38 stimuli, she was пїЅhooked. Estimating overdiagnosis in low-dose computed tomography screening for lung cancer: a cohort examine.
The natural anxiousness that accompanies a detailed call, such because the failure of the diverпїЅs air provide, or egress from a helicopter misplaced at sea, may masks a state of confusion caused by an arterial gas embolism to the mind. Espinel-Ingroff A, Stockman L, Roberts G, Pincus D, Pollack J, MarChen Y C, Eisner J D, Kattar M M, Rassoulian-Barrett S L, Lafe K, ler J. Duodenal and/or esophageal atresia end in an inability of the fetus to swallow amniotic fluid (reply c) anxiety xanax forums <a href=https://postpartumhealthalliance.org/medreviews/verification33/purchase-cheap-wellbutrin-sr/>purchase wellbutrin sr 150mg without prescription</a>. Characterization of a secure, hypertensive rat mannequin appropriate for the

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