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

јфоризм
∆изнь - это кpосс, в котоpом каждый стpемитс€ выpватьс€ впеpЄд, чтобы пpийти к финишу последним.
 
ѕоиск


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



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

VatrasObenseses | 07-06-22 10:04
Lesions are usually devoid of hair follicles and different <>8,50] (it could possibly be related to the upper price of earlobe piercing in functioning adnexal glands. One of the good difficulties in assessing the results of frenulotomy is in figuring out which sufferers have clinically important issues associated to ankyloglossia. The particular person should be clinically assigned as a very gentle case/ pre-symptomatic case by the treating medical officer impotence over 40 <a href=http://www.mafa.org/vital/buy-cheap-apcalis-sx-online-no-rx/>purchase apcalis sx mastercard</a>.
These include climate, skin condition, scars, weight changes, food regimen, activity, body form near the stoma and the character of the ileostomy output. In addition to for sufferers who have not fully responded to an sufficient being brought on by inadequate therapy, poor response might acute phase treatment over a adequate time, typically end result from multiple other components (413) which are enumer fourвАУeight weeks. However, there was a big discount in supply less than 32 weeks of gestataion in cerclage group with 3 or extra second-trimester deliveries, and no histories of cervical surgical procedures antibiotics prostatitis <a href=http://www.mafa.org/vital/buy-cheap-amoxil/>purchase amoxil 650 mg free shipping</a>. The results have been comparable to these in other medical literature, but had a lower subsequent surgery fee of approximately 5%. Heat with frequent agitation and boil for 1 minu


Darmokaugmend | 06-06-22 01:26
An equally crucial component was the availability of produce that met business wants. There are three forms of mechanisms of interest to the diagnostician: вАҐ Those that management the вАШinside milieuвАЩ by keeping temperature, tissue perfusion, blood gases, and biochemistry constant. To obtain these lower hemoglobin A1 C values, adjusting the insulin doses are necessary antibiotics for prevention of uti <a href=http://www.ouramb.org/results/order-zibramax-no-rx/>best 500 mg zibramax</a>.
The nature of this beneft Metabolic syndrome (obesity, diabetes mellitus) is related to the biologic effect that smoking has on decreasing the Nulliparity, infertility endogenous levels of estrogen, probably the alteration of liver Irregular menstrual cycles metabolism of estrogen, and the impact smoking has on early Polycystic ovarian syndrome onset of menopause. Similarly, trials shouldn't be conducted deemed appropriate, mixture updates should be supplied abroad solely as a result of lack of or much less at predetermined occasions or on demand. Maternal rubella may cause defects in both eye (fourth to sixth weeks of gestation) and ear (seventh to eight weeks) antibiotics for mastitis <a href=http://www.ouramb.org/results/buy-cheap-azimycin/>cheap azimycin 500mg free shipping</a>. A single haloperidol arm was included as a comparative treatment in 1 of the two trials, however this trial did not evaluate these 2 medicine on the total vary of clinically related doses for each. The studie


JerekveM | 04-06-22 04:08
Increased expression in early tumour differentiation and tumour proliferation has indicated that it may probably be used as a tumour marker(19, seventy one-75). Severe Disease: If ceftazidime or a carbapenem usually are not available, ampicillin/sulbactam or other intravenous beta lactam/beta-lactamase inhibitor mixtures might characterize viable, albeit much less-confirmed options. Physical examination at the time of examination revealed regular vital signs, and a mid-peaking systolic murmur with a preserved S2 auscultated loudest on the proper higher sternal border virus yahoo <a href=http://www.ascdayton.org/presentation/purchase-hemomycin/>generic 250mg hemomycin visa</a>.
J Eur Acad Dermatol Venereol 2009;23: nearer look at these situations and an method to intertriginous eruptions. Alcohol is the most used psychoactive substance on the planet and Conclusion: these new genetic threat components correlate with abuse can result in dependancy. Hypoxia is one other potential, although much less apy to the brain can induce vasculopathy, one other pocommon, reason for seizures in cancer sufferers anxiety zone hypochondria <a href=http://www.ascdayton.org/presentation/purchase-clomipramine-online-in-usa/>10mg clomipramine for sale</a>. Kleinoeder1, vitro data to predict the overall in vivo pharmacokinetics of drugs or chemical substances J. Table 5 provides advised Transjugular Intrahepatic Portosystemic calorie necessities based mostly on targets of therapy. Anabolic steroid


Benitoepity | 24-05-22 15:24
Incidence, prevalence, and survival of continual pancreatitis: a inhabitants-based research. By distinction, anabolism is a divergent course of in which a few biosynthetic precursors kind all kinds of polymeric, or complex, products. A stoma provides another path for urine (within the case of a urostomy) or stool (in the case of a colostomy or ileostomy) to depart the body diabetes insipidus blood glucose <a href=http://www.fsrt.org/training/purchase-online-actoplus-met-no-rx/>purchase actoplus met 500 mg with visa</a>.
Most cases develop Material and methods: This crossectional study was accomplished at a tertiary care Cushing syndrome due to prolonged use of steroids. Low turnover of workers increases patient Combined appropriate therapy, thereby enhancing affected person outcomes. Silicone provides optimal absorption of the shock generated from everyday and excessive-impression heel strike acne 404 nuke book download <a href=http://www.fsrt.org/training/buy-policano-online-in-usa/>policano 30 mg on-line</a>. Binge consuming disorder occurs in about 2% of community cohorts and is widespread among pa tients seeking treatment for weight problems at hospital-affiliated weight programs (1. Medical Policy In General data, Equipment Requirements, revise listing of acceptable tools, particularly acceptable substitute equipment for imaginative and prescient testing. Patients present at all ages, primarily with dysphagia for solids/liquids and bland regurgitation acne jeans mens <


AltusHow | 22-05-22 12:04
Rheumatic fever or any rheumatic heart disease is said to be energetic or recurrent. The fruits are historically used for cuts and ulcers, for pulmonary ailments and fevers. Technicians must take special care to maintain the mice separate and to disinfect the caging system and altering areas to forestall the spread of any pathogen that might be current pulse pressure lying down <a href=http://www.phoenixbiotechnology.com/properties/order-cheap-labetalol/>labetalol 100 mg with visa</a>.
Figure 1 also defines levels of blood glucose beneath which a prognosis of diabetes is unlikely in nonвАУpregnant individuals. The effect of mannitol on renal estimation from urea nitrogen look and creatinine manufacturing function following cardio-pulmonary bypass in patients with regular throughout steady renal substitute therapy. In Beijing (Monday, June need bourgeois, capitalistic ways and tradition contaminating 13) (Document half) administering medications 6th edition <a href=http://www.phoenixbiotechnology.com/properties/order-depakote-online-in-usa/>purchase depakote 250 mg otc</a>. Thus, elective surgery in sufferers with Postoperative danger discount methods have centered on acute viral or alcoholic hepatitis ought to be delayed until the promoting lung expansion by way of the use of incentive acute episode has resolved. Therefore, one other measure of a strong fnding is the number of diferential diagnoses required to elucidate, say ninety nine% of patients with that fnding. Ceftri


Givessbornelp | 21-05-22 08:39
Although the deformity may not at all times deepen, it's unlikely that it's going to resolve spontaneously. The C and N terminals of those proteins are crosslinked to provide tensile energy to the bone. The primary organics which have been detected are chloroform, bromodichloromethane, dibromochloromethane, bromoform, carbon tetrachloride, and 1,2-dichloroethane allergy treatment while pregnant <a href=http://www.phoenixbiotechnology.com/properties/buy-prednisolone-no-rx/>generic prednisolone 10mg otc</a>.
This is a translation of the recommendations in on a regular basis language, with emphasis on questions important to patients. Plateau Pressure At the end of a full inspiration, the airflow out of the patient is capped and the stress in opposition to the cap is examined. Comments: Mild (one hundred fortyвАУ159/ninetyвАУ99 mmHg) or moderate (one hundred sixtyвАУ179/100вАУ109 mmHg) persistent arterial hyper- Note: rigidity do not appear to cause headache hiv ear infection <a href=http://www.phoenixbiotechnology.com/properties/order-online-nemasole/>best order for nemasole</a>. For some most cancers managing group categorization, or the lower or much less websites, the situation and quantity or burden of superior subcategory ought to be used. Fetal growth retardation <10% percentile of weight for <5% percentile of weight for <1% percentile of weight for gestational age gestational age gestational age Definition: A dysfunction characterised by inhibition of fetal development


Mariustaisy | 20-05-22 09:46
This topic deals with the problem of the way to allocate scarce resources in such a method that the advantages вАУ measured in one way or one other - from using these sources are maximised. This additionally results in the general use of antibiotics in the neighborhood and will result in pointless imaging. Inflammation, coagulopathy, and the pathogenesis of a number of organ dysfunction syndrome antibiotics for acne brand names <a href=http://dtekerala.gov.in/medcontent/buy-ultrabac-online-in-usa/>buy ultrabac with a visa</a>.
You have extreme restrictions on value, well being & security or environmental impact so finding a good solvent mix may be very exhausting. A easy fracture happens when the suture material that takes the longest to soak up bone breaks cleanly into two separate pieces. Renal pyramid Inferior vena cava Adrenal (suprarenal) glands Inferior vena cava Abdominal aorta Prostate gland (in males) hilum renal medulla proper kidney ureteral orifice left kidney renal pelvis ureter urinary bladder renal artery renal vein urethra urinary meatus renal cortex Check your solutions by referring to Figure eleven1 on page 310 top antibiotics for acne <a href=http://dtekerala.gov.in/medcontent/buy-cheap-aziphar-online-no-rx/>order genuine aziphar online</a>. National Academy of Clinical Biochemistry Laboratory Medicine Practice tips: Recommendations for the usage of laboratory tests to assist poisoned patients who present to the emergency division. Enzymes stored in these


LucaSmumthact | 19-05-22 21:57
Intratumor heterogeneity in human medication Sackler colloquium: evolutionary on Hereditary Breast and Ovarian Cancer glioblastoma refects cancer evolution- views on well being and medication. But if insomnia is the rule, not the exception, you have to go after it as a particular problem. Dysphagia, shoulder weak point, and cardiovascular instability are also indications that mechanical ventilation could also be needed symptoms vitamin b12 deficiency <a href=http://dtekerala.gov.in/medcontent/purchase-cheap-quetiapine/>discount quetiapine express</a>.
It is known by these expert understand that the particular type will depend on the pH. Foreign bodies can mimic croup, it is important to ask about a possible choking occasion three. Carcinoma of the urethra is Adult kind occurring in adults over 40 years of age and uncommon acne quiz <a href=http://dtekerala.gov.in/medcontent/order-online-isotane-cheap-no-rx/>buy isotane us</a>. Add one hundred fifty 300ml recent frozen plasma at the end of every pheresis session if sufferers have pulmonary the double-antibody positive patients do not appear to have hemorrhage, or have had recent surgical procedure, together with kidney biopsy. While this is able to require an extra effort from the Licensing Authority, it may present a continuing and critical evaluation of the present medical necessities and could present whether or not they achieve their function. Other causes of a illness, Behcet's disease) nodular panniculitis, which may s


YokianFlubsFlut | 16-05-22 18:37
However, suppression of a nursing infantвАЩs immune function is a potential complication. Soft tissue sarcomas and navy service in Vietnam: A case comparison group evaluation of hospital sufferers. This supplies a measure of the pressure that the ventricle should overcome to eject blood erectile dysfunction treatment washington dc <a href=http://www.sttheresechesva.org/session/buy-cheap-vimax-online-no-rx/>buy vimax 30caps low cost</a>.
Gastric emptying of lactose and glucose- galactose in patients with low intestinal lactase activity. This might be accomplished by treating few ml of urine with few ml of hydrochloric acid giving a white ring on the junction of the 2 fluids. Shock and disseminated intravascular coagulation are common in bacteremia as a result of B virus for mac <a href=http://www.sttheresechesva.org/session/purchase-online-colcout-cheap-no-rx/>cheap 0.5 mg colcout with visa</a>. Active-obligation girls and wives of active-responsibility males had lower rates of bodily violence by an intimate companion, in accordance with the study (28. In adults, this tumor tends to occur within the body of the cerebellum, particularly towards the edges. The physical examination may also provide useful With massive bleeding, the necessity to management the air clues to the analysis womens health letter <a href=http://www.sttheresechesva.org/session/buy-female-viagra-online-in-usa/>buy female viagra visa</a>.
Subject to Notice of rights 256 Pancreatitis Management of small-


Joeydrainny | 13-05-22 17:25
With stable tumours there's also a (relative) scarcity of erythropoietin (Miller 1990). Hemoglobin H and Hemoglobin Barts are both ineffective, with no efficient oxygen carrying capability. Effects of morcellation on longthe Society of Laparoendoscopic Surgeons / term outcomes in patients with uterine Society of Laparoendoscopic Surgeons treatment xanthelasma eyelid <a href=http://www.skinbio.com/medlib/order-amoxicillin-online-no-rx/>cheap 500mg amoxicillin otc</a>.
Interviews have been accomplished with eleven,161 respondents of whom 4762 had been males and 6399 were women. The preliminary ibuprofen serum plasma degree Jersey - United States, 2 Division of Nephrology, The Childrenпњљs was 330 ?g/mL (therapeutic vary is 10-50 ?g/mL). Every Household detergent is adequate for many rou working surface together with your sofa, foor and tine environmental cleaning virus jc <a href=http://www.skinbio.com/medlib/purchase-cheap-misultina-no-rx/>order misultina 250mg on-line</a>. Journal of the American Academy of Child and Adolescent Psychiatry, 39(eleven), 1396пњљ 1405. The alternative of aspirin, clopidogrel, or dipyridamole plus aspirin should balance the fact that the latter are simpler than aspirin however the fee is higher. Precursor to product ratios are particularly useful in distinguishing the totally different enzymatic defects symptoms you have diabetes <a href=http://www.skinbio.com/medlib/buy-liv-52-online-in-usa/>order liv 52 mastercard</a>. Due to the severely decr

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