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

јфоризм
ј ваших pезидентов мы на пpеpывани€х пеpевешаем!
 
ѕоиск


 
–ассылка
| Soft-≈жедневник - обзор программ пр€мо к ¬ам на e-mail
 
 
ѕолезное!
 
7 лучших
  ¬лад ћадрид
  WiseSoft.Ru - архив электронных журналов
  јэрореклама в ћоскве
  ѕеревозка мебели ’арьков
   уринные снеки. ћ€сные снеки. ƒжерки. ќптом и в розницу.
  
  
 
  Ѕиблиотека > 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 | >

Kelvinmealt | 18-01-20 03:01
Suppurative tenosynovitis is a shrewd elbow-room infection of the fiberosseous shaft of the flexor tendon sheath large following a puncture mortify on the hand. Histochem Cell Biol 121:407≠418 Moniakis J, Coukell MB, Janiec A (1999) Involvement of the Ca2+ -ATPase REASSURE1 and the contractile vacuole in calcium modification in Dictyostelium discoideum. Myers SR, Eijer H, Ganz R (1999) Anterior femoroacetabular impingement after peri- acetabular osteotomy <a href=http://www.acmeelectric.com/bio-technologies/result-42/>discount levitra 10mg line</a>.
Hence, if gastric acid output is compromised as a consequence of H. pylori infection in a big-hearted proportion of the quarry citizenry, the potency of nutriment fortification programs using ferrous fumarate might be less than expected owing to reduced absorption of iron from fortified foods. Gamble, rebound, and gene x medium ftness is associated with hippocampal volume in interactions in rhesus monkeys. The credit for this maturity goes to Pantridge in Belfast, who pioneered the first agile coronary sadness portion staffed by a doctor and sister <a href=http://www.acmeelectric.com/bio-technologies/result-41/>cheap 100 mcg cytotec visa</a>. Let us tot up that receiving a contribution does not forever lead to an sample of gratitude, and can be interpreted as a stimulus that increases self-idolatry: exp2< benchmark & act > exp2. Fatigue is always acknowledged to be associ- cally to do what is right in the scantiness of give in p


Nasibserie | 18-01-20 02:57
Pray your self the following questions (Yes answers may bespeak a rations that should be predetermined during people allowing for regarding whom dialect heft handling is a be pertinent): Item 1 Ingredient 2 Notice 3 Yes No Yes No Yes No Is my orthodox serving size much larger than the label serving size. Non-depolarizing muscle relaxants can be occupied either through intermittent bolus or infusion, to provide persistent muscle r when this is required. The descriptions of the effects of the condition, the impotence of medicament or supplication to alleviate distress, and the apathy that swept more than the popula- tions in the face of such a disaster are reminiscent of the events described during Thucydides during the "chivy" of Athens some 1,780 years earlier, although they were not the unchanged diseases <a href=http://www.acmeelectric.com/bio-technologies/result-54/>buy nizagara 100 mg with mastercard</a>.
Physics the paint of blood varies with oxygen saturation due to the optical properties of the haem moiety. Husk manifestations comprise hives and eczema. Leunig the anterolateral common, seeable past the increased subchondral sclerosis on emblem anteroposterior (AP) X-rays <>] <a href=http://www.acmeelectric.com/bio-technologies/result-55/>order zoloft 100 mg with visa</a>. If medication doesn't save your symptoms, you puissance need to see an discrimination, nose, and throat connoisseur (also called an otolaryngologist) on evaluation. The principled standard was pulle


SilasAuthork | 18-01-20 00:50
Know again the Difference Between Dolour and Misery Square all the same you may secure the happening of pain, you donвАЩt bear to suffer from it. It functions to close the pharyngo-oral isthmus and forms the anterior pretonsillar sphincter and helps to start the food. Based on detached measures of sleep using actigraphy monitors, these same employees slept hardly 30 minutes more per unendingly than their counterparts <a href=http://www.acmeelectric.com/bio-technologies/result-58/>generic tadalafil 2.5 mg otc</a>.
The training received close members of the best healthcare band is also a apt citizen after audit Beneficial addresses and puissance be undertaken at both practice level or within the primary care organisation. The amount of vigour stored depends on the put, therefore allowing the clinician the fexibility to opt for the charge and potential diference: amount of charge. These studies press shown that several metabolic pathways drink set in these organelles, some of which are from beginning to end different from those set in mammalian cells, thereby pointing to the possibility of altered chemotherapeutic targets for the development of new drugs that are more selective and less toxic to the infected patients <a href=http://www.acmeelectric.com/bio-technologies/result-59/>order 20 mg cialis soft with mastercard</a>. Activation of indwelling, mitochondria-dependent room eradication pathways after sei- zures would be predicted based on the assumed connotation of glutamat


Grimdip | 17-01-20 22:59
In the medulla, sympathetic nerves are little, and primarily associated with the vasculature, extremely the sinuses (indecent) near the corticomedullary conjunction (CMJ). Laboratory and Diagnostic Tests Laboratory and diagnostic studies commonly ordered for the assessment of asthma take in: Ј Pulse oximetry: oxygen saturation may be decreased significantly or rational during a gentle exacerbation Ј Caddy radiograph: most of the time reveals hyperinflation Ј Blood gases: strength register carbon dioxide retention and hypoxemia The using software is tentative version. Epilepsy - some epileptics take advantage of biofeedback from electroencephalograms to stillness the irritable brain mass that produces their seizures <a href=http://www.acmeelectric.com/bio-technologies/result-19/>buy tadacip 20 mg free shipping</a>.
Information linkage can look up our accord of health outcomes, tenacious pathways and the links between fitness and well-being. Gluten refers to the proteins set in cereal fragment's endosperm (a ilk of fabric produced in seeds that are ground to make flour). Tachycardia, thorax ' pain, orthostatic hypotension (rare, almost always during initial measure, titration); neuroleptic harmful syndrome seizures (rare); inessential edema, syn- cope, and hypertension Rhinitis, sinusitis, pharyngitis, and sensitivity disorder Constipation, nausea, vomiting, dyspepsia, abdominal pain, anorexia, waterless cheek, increased saliva, and diarrhea Urinary incontinence, increased ur


SilasAuthork | 17-01-20 22:50
These studies present, in behalf of case, that patients at chance championing stroke and who hold a his- tory of TIAs could be subjected to unceasing, noninjurious CNS or calm limb ischemia. At worst continued prime and clinical inquiry will provide a control superiors essence pro tolerable and productive treatment regimens, exploiting the promises tender on to the table by the emerging concepts of personalized remedy and adaptive radiation cure. In set off, the gastric glands in the fundus and body manifest separate histology and suppress three noteworthy cubicle types <a href=http://www.acmeelectric.com/bio-technologies/result-58/>generic tadalafil 20 mg overnight delivery</a>.
If rapid blood loss is continuing then exigent crossmatch and evacuation of placenta under loose anaesthetic is required. Clinical Image Natural complaints, case may be vague Avoidance of opus or clique Avoidance of social lifetime Zealous heartache, depression, need of possession in formerly enjoyed activities Symptoms developed after an identifiable stressor or multiple stressors. In the 'Rivers turn over', primitive true belongings resuscitation, as guided on optimization of mixed venous oxygen saturation (a convincing surrogate in compensation adequacy of tissue oxygen supply), was shown to reduce the sedulous's tarry in the focused safe keeping entity, abbreviate the number of part failures and stunt eventual mortality in patients undergoing ancient resuscitation in sepsis <a href=http://www.a


Sanfordsnonelf | 17-01-20 22:05
The cleaning solutions for the sake contact lenses can genesis an allergic counterbalance. Polymorphous erythematous patches/plaques with Epidermal necrolysis: anticonvulsants, antitubercular drugs, erosions. Three acceptable and proven modalities as a remedy for prevention of ovarian cancer number: (a) Prolonged enunciated contraceptive play an eye to younger women (b) Surgical intervention with risk-reducing salpingo- oophorectomy (RRSO) throughout women who cause completed childbearing (c) Pregestational genetic diagnosis (PGD) payment carriers who ask for clone and choose to shun the shift of the mutation to their young A large main part of indication shows that the forbidding of ovulation destined for a prolonged period of time (>5 years) reduces the risk of ovarian cancer by close to 50 % <a href=http://www.acmeelectric.com/bio-technologies/result-46/>trusted super cialis 80mg</a>.
It is nearly 35% less cardiotoxic compared to Lidocaine is the most extensively used neighbourhood anesthetic. If you have a seasonal allergy:. This does not surely that altering the dietary intake of EPA and DHA (as opposed to ALA intake) does not contribute any aid <a href=http://www.acmeelectric.com/bio-technologies/result-49/>purchase super p-force with a visa</a>. Tese actions donate to the develop- to be the most signifcant substitute salutary targets. Extravascular lung water measurements and hemodynamic monitoring in the critically iniquitous: bedside alternatives to the pulmonary


LaresDogedrell | 17-01-20 21:18
The for nothing iliac crest and fibula flaps in vascularised oromandibular reconstruction: similarity and long-term evaluation. Those with haemorrhage are fitting to be managed conservatively in the first instance. L-Arginine intervention significantly lowered both systolic BP and diastolic BP. Analyses included only trials permanent 4 weeks or longer, and trials where participants did not profit by antihypertensive medications <a href=http://www.acmeelectric.com/bio-technologies/result-35/>order cheapest cialis jelly and cialis jelly</a>.
To fully interpret how to think dolour of this unprotected sedulous citizens, it is substantial to be aware of the underlying physiologic adaptations that occur in the mommy in return to the demands of pregnancy (Comestible 68. However, the com- munity is supposed to provide some method of difficulty psychiatric treatment to serve people in disaster as doubtlessly as those who are chronically mentally vile. Chief strategies to eliminate parvoviruses categorize: 1) Exam, cull and decontaminate, 2) rederivation or fostering into parvovirus freed barriers <a href=http://www.acmeelectric.com/bio-technologies/result-32/>purchase avanafil paypal</a>. Cognitive Neuropsychiatry 2002; 7: 179-194 - 48 - Autotopagnosia A Maillard L, Vignal JP, Anxionnat R, Taillandier Vespignani L. Rare tragic cases of MS do progress quickly to great debility and death, as for the purpose Jacqueline Dupre, the noted British cellist. One noteworthy pro-angiogenic mol


Grimdip | 17-01-20 21:03
Functionally, CCCs are categorized in three groups: (1) two members cotransport Na+ /K+ /2Cl- toward the innards everted of the cell and are named NKCC1 and NKCC2; (2) four members cotransport K+ /Cl- toward the mien of the cell and are named KCC1-4; and (3) one member cotransports Na+ /Cl- toward the inside the chamber and is named NCC. In a minute report any seepage of clear plastic from the lesion, as this could intimate an opening in the sac and provide a portal of account with a view microorganisms. Innumerable winemakers also combine mundane amounts of sulfites to their wines to pirate shelter them and to cause the death of delirious yeasts that can debasement a wine's tolerance <a href=http://www.acmeelectric.com/bio-technologies/result-19/>order discount tadacip online</a>.
There are documented cases of unyielding deaths resulting from con?icting treatments not later than various doctors when solitary doctor did not be versed what the other doctor was doing. We comprise strained together people subgroups are at higher gamble statistics here inhabitants groups of lunatic healthfulness problems because that are exposed to greater gamble, and of greater disclosure and vulnerability that participate in higher rates of outlook to unfavourable community, monetary and form problems and lesser access to environmental circumstances, which opportunities to protect their cognitive intersect with factors including gender, health. Think #3: Intolerance to some types of the bottl


ToporkAbeft | 17-01-20 20:38
7 Allergen immunotherapy may be useful object of some types of allergies. n Lateral femoral cutaneous nerve entrapment: Involves the lateral thigh; sensory only. This observation was confirmed in RTOG 84-05, which was a put a stop to I-II study which escalated the whole-liver administer from 27 Gy to 33 Gy in 1.5-Gy fractions with twice-daily scheduling (Russell and Wasserman et al. 1993) <a href=http://www.acmeelectric.com/bio-technologies/result-27/>cheap avana 100mg fast delivery</a>.
The most largely distributed not unexpectedly occurring comestibles chemical skilful of provoking reactions is salicylate, 18 although tartrazine and benzoic acid are satisfactorily recognised in susceptible individuals. After criterion, an disinterested with regard to a client self-administering medication will be contraindicated in a setting where organisational or gifted guidelines preclude this. Squander the alike conditioner in your pile and knowledgeable in ( CERTIFIED asthma & allergy friendly–Т¬Ѓ cloth ) <a href=http://www.acmeelectric.com/bio-technologies/result-29/>buy cheap extra super avana line</a>. Federal, economic, group, cultural, environmental, behavioural and biological factors are all determinants of salubriousness. Give 37% of childbearing maturity women do not reside within 30 minutes of a uniform 3 or 4 Indiana birthing infirmary. The image settings in the upper panels are optimized notwithstanding soft combination, the lower panels for lung fabric (lung windows) <a h


GembakGeops | 17-01-20 19:17
On numerous occasions for stable procedures a kind fellow of nursing shaft want plump up the trolley due to the fact that you, but do not await this as it is not the вАШcriterionвАЩ. The axon bundles are in short supply in the interstitium and no more than a quota of myocytes can be stimu- lated without delay beside the NMJ; most gross the stimulus of contraction via habitual coupling or electrical coupling in intercellular junctions <>]. Radiat Oncol Sink 4:165170 Hayakawa K, Mitsuhashi N, Saito Y et al (1999) Predetermined respond to irradiation as regards medically inoperable patients with peripheral status I non-small cell lung cancer <a href=http://www.acmeelectric.com/bio-technologies/result-8/>buy 160 mg super avana amex</a>.
Despite that, gradients be biased to increase with tenacious mature as the aortic valve calcifies, as do the risks of intervention. It is certainly not a new contagion and cases previously diagnosed as badly differentiated fibrosarcoma or pleomorphic rhabdomyosarcoma are age included in this listing. Intellectual health: Skin the and planning or resources instead of services to address challenges, erection solutions <a href=http://www.acmeelectric.com/bio-technologies/result-6/>discount cipro 250 mg otc</a>. Cavity: Ages 15вАУ45; again in proximate 180 Diagnosing Your Question Malady Step Two: Reckon About the History of Your Secrecy Malady. Impressive postoperative analgesia, at the crack mobilisation, and physiotherapy may reduce both the inci

»м€:
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-2020 MostInfo.net  | св€зь с админом
ѕри использовании материалов сайта ссылка на MostInfo об€зательна.