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

јфоризм
Ѕогоматерь.ico
 
ѕоиск


 
–ассылка
| 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 тыс€ч раз лазил в базу) в) увидеть сообщение об ошибке в результате попадани€ в строку спецсимволов €зыка запросов. ¬о-вторых, некоторое удобство дл€ пользовател€ - постраничный вывод и подсветка.



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

ZubenBexpede | 05-06-21 10:07
Complete cochlear implant analysis should be performed by a professional audiologist. For households that report each hire and utilities, the three primary wants expenditure sample-weighted averages for meals, utilities and rent are added to calculate complete primary needs expenditure per (equivalent) person. Peripheral the Management of Patients With Lower Extremity Peripheral arterial disease: analysis and management medications zocor <a href=https://www.fastmap.com/wp-content/laboratory-practice/order-coversyl-online/>purchase coversyl uk</a>. However, before this take a look at may have added worth, there may be need for higher treatment options. A variant of this foraminal compression take a look at includes rotation, facet bend, and slight extension of the neck with the appliance of axial stress to the head.
Mode of Transmission Generally, West Nile encephalitis is unfold by the bite of an infected mosquito. These proportions steadily change as the arteries department many occasions and turn into smaller till within the arterioles (the smallest arteries) the tunica media consists almost completely of smooth muscle. Medical Policy In Pharmaceuticals (Therapeutic Medications) part, change title of Antihistaminic and 487 Guide for Aviation Medical Examiners Desensitization Injections to incorporate the word Allergy medications 122 <a href=https://www.fastmap.com/wp-content/laboratory-practice/buy-topamax-online/>buy topamax 100 mg with visa</a>. Cerebral damage (irradia


Ur-Goshembesteda | 22-05-21 17:26
In the past, in several parts of the world, the pterygium was eliminated They do that by using a marking and cutting devise referred to as a Corneal through radiation plaques, which worked by inserting a small steel Punch. Serine and glycine are more abundant than the two others and therefore are the principle sources. The rate of malignant tumours ranges from 10-22%, and < 50 circumstances have been reported (21-23) <a href=https://pd-trak.com/wp-content/conference/buy-online-betapace/> blood pressure gauge cheap betapace 40mg with amex</a>.
About 11-13 days after ovulation, if there isn't any implantation, ovarian production of progesterone and estradiol starts to fall of. It is definitely an organising scheme which allows the evaluation of various skills but technique of standardised and objective testing. If so, then other (unde ter, <10 ?m) is more efficient than that by bigger ?ned) components in addition to the level of preexisting immunity droplets <a href=https://pd-trak.com/wp-content/conference/buy-online-npxl-cheap/> himalaya herbals review purchase genuine npxl on line</a>. The again ought to be rigorously examined in patients with hip complaints, including analyzing for. Choanal atresia, choanal stenosis: Congenital absence (or narrowing) of the passageway between the nose and pharynx because of a thick bone or thin membranous bone. Multifunctional antimicrobial peptides: therapeutic targets in a number of human diseases <a href=https://pd-trak.com/wp-content/


Muntasirpaf | 13-05-21 21:50
The appearance of colonies, or the power or incapability to kind colonies on explicit media can, in some circumstances, be used to identify the genotypes of bacterial cells. Forty freshly extracted intact cal specimens are shown at both concerned in group service vs. Each sarcomere is around 2 –Ю—Шm in length with a three-dimensional cylinder-like organization and is bordered by structures called Z-discs (also called Z-lines, because pictures are two-dimensional), to which the actin myoflaments are anchored (Figure 3) cholesterol quail egg <a href=http://alleneng.net/medical-solutions/account476/>20mg atorlip-20 amex</a>.
In complement to Regulations 883/2004 and 987/2009, which regulate the coordination of social security techniques, the Directive improves affected person selection as sufferers can go to different Member States for therapy, and obtain reimbursement for this treatment if they're entitled to it of their residence nation. Creatine, too, performs a key position in cellular vitality formation and is decreased within the brain cells of hyper Diagnostically, the presence of acidosis, ketosis, hypoglyce ammonemic animals as a result of altered creatine transport and mia, and low bicarbonate ranges indicate that the root explanation for synthesis. Despite this, their staff ship a and even transfer training programs will extremely advanced stage of invasive trauma train that you that you can not obtain a care and carry out airway skills, chest de nice deal in terms


GamalTow | 12-05-21 09:33
The threat reduc tion was estimated to be 88% for coronary coronary heart illness and eighty% for stroke. IвАЩm nonetheless capable of assist with cooking and operating the women to high school in the intervening time. In the occasion that a patient does not respond nicely to the preliminary agent, a unique agent within the similar class is Page 247 appropriate quadriceps fungus <a href=http://alleneng.net/medical-solutions/account78/>purchase lotrisone 10 mg on line</a>.
Cholesteatoma needs radical mastoidec Inward spread towards inside capsule: Paralysis tomy, which removes the irreversible disease and exterior of leg is followed by the paralysis of arm and face. Prescribers must take full accountability for prescribing unlicensed medicinal merchandise and unlicensed uses or administration of licensed products, when such use falls outside the suggestions. Outbreaks as a result of subspecies E meningo cillin/clavulanic acid 875 mg/a hundred twenty five mg orally twice daily, or septica and E anopheles have been related to contami clindamycin can be used (600 mg intravenously every 8 nated water sources and have typically occurred in well being-care hours or 300 mg orally every 6 hours) arterial thrombosis <a href=http://alleneng.net/medical-solutions/account79/>generic aceon 2 mg overnight delivery</a>. Malignancy, infection, drug induced Stop any medicine that may cause hyponatraemia. This section ciation of the significance of involving it in study improvement will chron


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

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