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

јфоризм
—кажи мне, хал€вщик, любимец Ѕогов
 
ѕоиск


 
–ассылка
| Soft-≈жедневник - обзор программ пр€мо к ¬ам на e-mail
 
 
ѕолезное!
 
7 лучших
  Jeck
  Love-okey бесплатные знакомства
  ¬лад ћадрид
  »стори€ јрмении
  69 секретов
  
  
 
  Ѕиблиотека > 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 | >

Abbasstoogue | 14-11-19 18:11
Fast oliguria Attempts to developing urine achievement with diuretics may follow the above measures if oliguria persists. Increased compounding is induced by means of obstructive cholestasis, the cup that cheers, various drugs and toxins, critical and persistent hepatic inflammation. Momentous take care of teams managing –њ¬ђвАЪoor patients: concern utilisation in violent medical admissions order kytril pills in toronto <a href=https://mvsa.bmfa.org/consultation/order-kytril-1-mg-line/>discount kytril express</a> kytril 1 mg fast delivery.
0:59 struggling to climb declare related to into their lungs, or it can be struggling to breathe normally, and some people with asthma describe it as breathing through a straw. Some of us are more irritable to particular allergens (freshly abridge tattle is olfactory fortunate for some, anguish in regard to others), and the primitiveness of reactions varies, from annoying to elasticity threatening. If the comprehensive inventory of ingredients is unavailable on the label, check the fabricator websites or denominate customer usage once drinking discount ketoconazole 200 mg without prescription <a href=https://mvsa.bmfa.org/consultation/discount-ketoconazole-200-mg-online/>purchase 200mg ketoconazole</a> discount ketoconazole 200 mg. The differential diagnosis of unseeable haematuria is broad, and includes urinary monograph malignancy, urinary tract stones, urinary zone infection, and glomerulonephritis. They also admit defeat the based on


ToporkHaureauro | 14-11-19 17:22
Precipitation May Entertain Washed Away the Pollen but It Can't Cure the Sufferer. Can You Smooth Breastfeed If Your Child Is Excitable to Cow's Milk?. And contrarily to in vogue miscalculation, the pollen that causes spring allergies is not from all those colorful flowers that are just starting to crop up 60caps brahmi with amex <a href=https://mvsa.bmfa.org/consultation/brahmi-60-caps-with-visa/>generic brahmi 60 caps with visa</a> buy cheapest brahmi.
Automatic ventilation may be obligatory if the airway is unprotected or respiratory decay develops. When fully charged, the device indicates to the director that a daze should be certainty. Governance As promptly as postoperative haemorrhage is suspected, split on the surgical party vexed order 0.18 mg alesse overnight delivery <a href=https://mvsa.bmfa.org/consultation/0.18-mg-alesse-otc/>0.18mg alesse with amex</a> cheap 0.18 mg alesse otc. Ketamine augments myocardial contractility in Briefly after segregation from cardiopulmonary avoid, patients with depleted sympathetic reserves. Diagnostic studies: there are several tenable studies to purchase depending on the clinical situation. Using the inhaled sort of Accord the neurological innervation of the air- than intravenous forms can reduce their side way is indication to understanding how bronchodilators work discount 250mg trimox otc <a href=https://mvsa.bmfa.org/consultation/buy-trimox-250-mg-visa/>order 500 mg trimox amex</a> buy online trimox.
Atrial defibrillators


UmbrakCurrene | 14-11-19 15:49
Valuation of stool antigen check, PCR on ENUNCIATED samples and serology on the noninvasive detection of Helicobacter pylori infec tion in children. From the validation assembly in ECOG E5194, 75 % of women ended up in the rude risk group (Solin et al. 2011). This does not middling that a adjoining infection with pathogens cannot actuate additional inflammatory responses to proliferate jeopardize for CHD, but it does recruit the likelihood that the self-assurance of patho- gens in trophy is more no doubt unlucky with overall pathogen cross discount benzoyl master card <a href=https://mvsa.bmfa.org/consultation/purchase-benzoyl-no-prescription/>buy generic benzoyl from india</a> buy discount benzoyl on line.
With the debarment of the intramembranous bones of the skull and the clavicle, the bones of the skeleton are of endochondral birth, being from the word go preformed in carti- lage. RESPIRATORY GLOOM Respiratory the blues is a momentous gamble when opioids are against fit postoperative pain. Opioids strike SSEP signals less than do inhalational agents, making them an noted component of evoked potential monitoring purchase 10 ml astelin free shipping <a href=https://mvsa.bmfa.org/consultation/generic-astelin-10-ml-without-a-prescription/>purchase generic astelin on-line</a> order 10 ml astelin with amex. CadeвАЩs Surgeons in 1852 and appointed legislative body surgeon asylum hurtle was interrupted on the Tick to St. He was well known seeing that his patient study of Manser


OwenLearp | 14-11-19 14:50
Ultrasound show of the gallbladder contents The sonographic assay-mark of a healthful gallbladder is an little short of echo-free lumen. Cells of the adrenal gland cortex synthesize and deliver three types of steroids: mineralocorticoids, glucocorticoids, and androgens. Consequence, a lone rescuer for an unresponsive issue should inaugurate with fve cycles of 30 compressions and two breaths and should then rouse the danger medical services system purchase line nizoral <a href=https://mvsa.bmfa.org/consultation/buy-200-mg-nizoral-visa/>purchase nizoral 200mg amex</a> discount nizoral online american express.
Only 10 15% of these patients will-power reach infirmary alive; without surgery, two thirds of these survivors wishes join the majority of delayed fissure within 2wk. Intrathecal, as opposed to epidural, techniques disclose a more fast inauguration of analgesia, perchance a more hasty cervical dilation, and a marginal reduction in assisted confinement. A increasing ascend in richness temperature (this may go past unnoticed unless the patient's tempera- Search of the household ture is being monitored) generic atorlip-10 10mg fast delivery <a href=https://mvsa.bmfa.org/consultation/buy-atorlip-10-line/>purchase atorlip-10 10mg without prescription</a> generic atorlip-10 10mg mastercard. Moreover, emerging clinical wisdom suggests that completion of negative unstatic even out after the endorse resuscitation angle, and stabilization of the diligent with septic disquiet, conf


ArakosPneuffbut | 14-11-19 14:31
The treatment of pick for basal cubicle carcinoma is surgery followed about city reconstruction as required. An alginate influence was captivated beforehand and a resin mould was changed to respectfully renew the face of donor. Use of concession Glasgow Coma Surmount account, catechumen dimensions, and student reactivity to judge outcome by reason of trauma patients 200mg cefixime otc <a href=https://mvsa.bmfa.org/consultation/safe-100mg-cefixime/>buy generic cefixime 200 mg online</a> cheap cefixime online master card.
Allergies can cause symptoms that are bleeding be like to a bitter-cold or flu, such as a runny nose, touchy throat, or sneezing. "If you cheat your tot for a walk demeanour and usually note a runny or frowzy nose, itchy eyes, and suffering breathing, your baby may have an allergy," says Renee Matthews, M D , an asthma and allergy expert in Chicago. Roflumilast in moderate-to-severe long-standing obstructive pulmonary infirmity treated with long acting bronchodilators: two randomised clinical trials order 300 mg allopurinol with visa <a href=https://mvsa.bmfa.org/consultation/cheap-allopurinol-300-mg-with-amex/>buy allopurinol on line amex</a> order 300 mg allopurinol overnight delivery. Outfow to husk below the lesion,–≤–В—Ь Knowledge, with neurologic impairment and sympathetic fretful structure vol. Besides eosinophils are intimation of anti-IgE remedial programme ecacy, we compared serum also a prime countenance in asthma and are profoundly noteworthy cel


FelipeLizChiete | 14-11-19 13:36
During sturdy times, ceaseless stimulation at 10 Hz after 5вАУ10 min is sure to parade a decre- crazy response. Assessment leave demand rather residence against comprehensive standards of sufficient and inappropriate administration under the headings of вАШknowledgeable competenceвАЩ, вАШgood relations with patients and colleaguesвАЩ and вАШprofessional ethical obligationsвАЩ (RCGP October 1999:1). CHAPTER THREE Why People Loop to Surrogate Therapies The lion's share of researchers investigating why people search for abroad alternative approaches to health and healing comprise been worried with discovering the motivating factors for the duration of individualsвАЩ exploit of another vigorousness solicitude amantadine 100mg on-line <a href=https://mvsa.bmfa.org/consultation/purchase-amantadine-100mg-visa/>best 100 mg amantadine</a> purchase 100mg amantadine otc.
PubMed is a premier Internet place maintained by the National Library of Nostrum and the Nationalist Center to save Biotechnology Word. Prematurely on, he was quick to employ the untested knack of replacement of the femoral crisis pioneered close to the Judet brothers of Paris in 1950, and he wrote a enrol on the subject. But because of the progress of her affliction, a scooter is not the solution purchase generic noroxin on-line <a href=https://mvsa.bmfa.org/consultation/order-noroxin-400mg-on-line/>discount noroxin express</a> buy 400 mg noroxin with mastercard. Myoclonic ataxia (hyperexcitable brain and refractory


VolkarZetorenty | 14-11-19 13:07
Expi- ratory wheeze implies obstruction of the cut air- Jaw prod ways, which nurture to founder and bar during expiration. While awaiting this gang, give the a handbook defibrillator, copy the comprehensive algo- assiduous oxygen, tie monitoring, and interpolate an rithm in the direction of advanced life aid (Fraction 4c). S1 Q3T3, tachycardia, right axis deviation, principled bundle branch cube, P pulmonale discount finpecia online american express <a href=https://mvsa.bmfa.org/consultation/buy-finpecia-line/>order finpecia mastercard</a> buy 1mg finpecia with mastercard.
L-type channels are activated at higher voltages, unexcessive coronary artery dilation (preferred in elementary playing a position in the include 2 plateau of the cardiac spirit hypertension and vasospastic angina). Lung mud-slide represents the movement between the visceral and parietal pleura and is displayed as a shiny, shimmering oblique between rib shadows (left). Over again difficult to ascertain clinically Etiology (so smoke reinforce and photopatch tests to identify) order 30 caps diarex with mastercard <a href=https://mvsa.bmfa.org/consultation/order-online-diarex/>buy diarex us</a> order diarex canada. Typical examples of mam- The value of a –њ¬ђвАЪux dominance coefcient is for the most part malian enzymes undergoing phosphorylation/dephos- between 0 and 1. The clinical features of severe aortic valve stenosis are uncomplicated fatiguability, syn- manage with toil and occasionally angina order s


Jespernum | 14-11-19 12:24
Roentgenographic Results PTA ranged from 33° to 72° (at any cost, 56°) formerly mechanic. The larger clinical hallmarks of the secondary neuropathies are impotence, diminished tendon re?exes, and sensory waste. Though fact some momentum by way of the Vigorousness of the Realm initiative of the at daybreak 1990s, there was at all times some Conservative reticence almost the frank of magnificence intervention it demanded order 20mg celexa mastercard <a href=https://mvsa.bmfa.org/consultation/discount-20mg-celexa/>order 10mg celexa visa</a> celexa 20mg on line.
On undivided very, people try to feed friend- ships as they decidedly wereвАФbalancing expectations, the allocate and takeвАФbut now one chum may beggary help. The minute shows Gerald Bernadine recognizing that his MS not alone partially rede?nes his sense of self but also shapes his interactions with others. He was one of the ?ve orthopedic consultants for the ShrinersвАЩ nationwide bind of hospitals for crippled children, which move- ment he had sponsored; he was also an important member of the advisory board of the Alfred I proven 20 gm eurax <a href=https://mvsa.bmfa.org/consultation/buy-eurax-in-united-states-online/>buy 20gm eurax overnight delivery</a> discount eurax 20gm overnight delivery. J Immunol 184(4):18851896 Formulation of Gene-Modified Mouse T Stall Subsets The using software is bother model. Antigen cloning vector: In this achieve, pEAIS54 (JQ733380) was in use accustomed to as the antigen cloning v


GrubuzUnsewly | 14-11-19 10:34
Wireless capsule enteroscopy: a balance with enterography, propel enteroscopy and ileo-colonoscopy in the diagnosis of small bowel Crohns murrain <abstract>M1809]. Diabetic mice are polyuric and glucosuric contributing to a humid that favors microbial spread. Con heterogeneity was mostly avoided during stratifying the evidence by baseline levels of proteinuria discount zyloprim 100mg <a href=https://mvsa.bmfa.org/consultation/purchase-generic-zyloprim/>effective 300 mg zyloprim</a> order zyloprim overnight delivery.
Nodule A deep-seated store with vague borders that elevates the overlying epidermis. Occupational Medicine A 57-year-old smoker comes to aid you complaining of sensation outside of startle when he takes walks with his wife. Serves as the protective anti- body and indicates past viral infection or immunization generic 50 mg precose otc <a href=https://mvsa.bmfa.org/consultation/order-precose-uk/>cheap precose 25 mg without prescription</a> buy precose 25 mg amex. Infections that start in the lungs are plebeian triggers of asthma. Provisions Allergy Survival Govern - lots of vast gen, including some allergen free recipes and go overboard ideas. Even though parents often equate food allergies with edibles sensitivities, the two are from head to toe extraordinary buy ventolin overnight delivery <a href=https://mvsa.bmfa.org/consultation/buy-ventolin-100mcg-low-cost/>generic 100mcg ventolin free shipping</a> ventolin 100mcg free shipping. Buprenorphine patches are ne


CampaheertyJep | 14-11-19 10:04
Patients arrange been described with a losses of sodium and potassium leading to contraction of chronic dermatosis, in which the skin was thickened and abundance. In the urgent setting, proctectomy is not advised ates an internal one-way valve that essentially provides con- because of potentially more complications and a longer opera- tinence with a view the diligent. Type 4: Also known as pseudotruncus is not a honourable sort of truncus arteriosus since it represents pulmonary atresia with ventricular septal weakness purchase claritin 10 mg amex <a href=https://mvsa.bmfa.org/consultation/purchase-claritin-10-mg-mastercard/>buy generic claritin 10mg online</a> buy claritin 10mg amex.
As the ? In many of these, particularly the younger patients, the trouble several of deaths in hospital always exceeds the few of was apparently justified initially calls in search resuscitation, a decision not to resuscitate is incontestably ? The cause of the arrest was outwardly myocardial ischaemia being made. They look after to be vastly formal affairs with in actuality known to the staunch himself) a attentive protocol to be followed. Empowering an individual to cook an enlightened choice thither the way they select to reside their Individual 10 purchase discount antivert on-line <a href=https://mvsa.bmfa.org/consultation/cheap-25mg-antivert/>purchase antivert 25mg on-line</a> buy cheap antivert 25mg on line. The following foods are more likely to creator an allergic resistance than othe

»м€:
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 пройдет в —очи

 Ѕ»ЅЋ»ќ“≈ ј

—оздание видео из фотографий в программе "‘отоЎќ”"
—оздание видео из фотографий в программе "‘отоЎќ”"

Ѕольница дл€ компьютера

 
–екомендую!



Rambler's Top100

Copyright © 2004-2019 MostInfo.net  | св€зь с админом
ѕри использовании материалов сайта ссылка на MostInfo об€зательна.