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

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

Афоризм
Дети - цветы жизни. Ягодки будут впереди.
 
Поиск


 
Рассылка
| Soft-Ежедневник - обзор программ прямо к Вам на e-mail
 
 
Полезное!
 
7 лучших
  Форум о заработке в интернет
  Центр GPS ГЛОНАСС навигации и мониторинга - НавиЦентр
  Сервисный центр
  Ntl-M Webpage
  Питомник кане-корсо DEO VOLENTE
  
  
 
  Библиотека > 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 | >

Domenikeracricky | 25-07-22 05:22
Lesions most commonly occur in diaper and intertriginous areas but in addition elsewhere on the body. Humanure composters can stand beneath the stars at night gazing on the heavens, and know that, when nature calls, their excretions won't foul the planet. DirectorsпїЅ Leadership Academy is available by way of the Center for Early Childhood Professional Development ( symptoms questionnaire <a href=http://www.jamesonministries.org/institute/order-asacol/>discount asacol 400 mg with amex</a>.
However survival is 35% decrease (in stool screening take a look at prior to now year or a sigmoidoscopy absolute terms) in adults 85+ than in ages 65-eighty four for or colonoscopy in the past 5 or 10 years, respectively. Extravasation Potential of Chemotherapeutic Agents A trained and experienced staff will greatly lower process-associated extravasation risk components. Isolation of micro organism from bone or adjacent constructions confirms the prognosis, but is constructive in only about one-third of cases acne extractions <a href=http://www.jamesonministries.org/institute/purchase-online-isotretinoinum-no-rx/>buy cheap isotretinoinum 40 mg line</a>. The lateral ventricle which causes neuronal destruction, metabolic problems opposite to the hematoma has turn into enlarged consequently typically trigger only minor neuropathologic modifications. Diabetic supplies together with lancets, alcohol pads and testing strips are in profit. In all events, 70% of participants did not total treatm


WenzelOsciday | 20-07-22 13:04
The consequence of oncogenic transformation is that tumour cells turn into impartial of these external development signaling factors in any regular tissue microenvironment. Erectile dysfunction is considered one of many symptoms of sexual issues including untimely ejaculation, increased latency time related to age, psycho-sexual relationship problems, and lack of libido. Doxycycline is appro lated price to repletefiuid standing over 48 hours, priate remedy for Chlamydia an infection and but not any faster antibiotics bladder infection <a href=https://maicc.org/lectures/order-ordipha-online/>ordipha 100mg free shipping</a>.
The sensitivity of all microscopy-based mostly strategies is dependent upon the skill of the laboratory technician. More invasive testing must be reserved for advanced sufferers, sufferers who have failed preliminary therapies. The node enlargement, and oropharyngeal manifesta- skin is rough, hyperpigmented, and a number of tions coronary artery quiz <a href=https://maicc.org/lectures/purchase-cheap-propranolol-online/>propranolol 80 mg lowest price</a>. Evaluation of the integrity, composition, and differentiation state of the genome is critical for the development of patient-particular pluripotent stem cells for therapeutic use (see Chapter thirteen). Moderate hyperhomocysteinaemia and immune activation in patients with rheumatoid arthritis. Despite these conclusions, no-until agriculture could not be practiced with out the arrival of herbicides and the


JesperCrunseben | 18-07-22 20:45
Unfortunately, when the affected person is discharged, What elements result in poor ache the depth or continuity of ache care is disrupted. Risk factors for high-order a number of pregnancy and a number of delivery after managed ovarian hyperstimulation: outcomes of four,062 intrauterine insemina- tion cycles. Neonates with a single mutation in factor V Leiden aren't at increased threat for thrombosis steroids and antibiotics for sinus infection <a href=http://www.scotsindallas.org/adviser/order-azifast-online/>generic 500mg azifast with amex</a>.
More than half of infants with • explosive, watery, foul-smelling stool on rectal omphalocele have related anomalies and preoperative examination. Transplantation of organs similar to the center could be an option, but it depends on a plentiful one cell type (hepatocytes) and has some in-constructed capacity source of transplant organs, and plenty of are briefly supply. It is strongly beneficial that children be checked annually submit chemotherapy to detect a secondary malignancy bacterial throat infection <a href=http://www.scotsindallas.org/adviser/buy-cheap-nitrofurantoin-online/>order nitrofurantoin 100 mg mastercard</a>. Shankaran S: Neonatal encephalopathy: remedy with hypothermia, the risk of pneumonia is 5% to twenty%. The dealing with and cutting of uncooked meat are prone to permit the release of meat aerosolized allergens into the environment, as already demonstrated in crab-exposed employees. Efficacy and security o


OsmundHeeltluro | 15-07-22 23:12
Comvax shouldn't be given before 6 weeks of age as a result of Haemophilus influenzae sort b component, and Twinrix just isn't yet accredited in the United States to be used in persons less than 18 years old. We addressed those points by using the totally different views of the staff to reach at a trustworthy interpretation and asking an professional Project Advisory Group to oversee and critique the evolving interpretation. A current case-management research in Greece (Bohlke et al, 1999) involved 820 girls with histologically confirmed breast most cancers who were in contrast with 1548 control ladies virus attack <a href=http://www.worldcell.com/development/order-goutichine-online-no-rx/>purchase goutichine toronto</a>.
Perhaps somewhat than trying to discover higher it becomes Sarafem (fluoxetine hydrochloride, Warner Chilcott). There was also proof that feedback could not only enhance a psychological well being outcome for particular person service users but additionally might accomplish that through an influence on healthcare skilled behaviour. However, there was a major lower within the variety of cardiac nuclei in feminine pups (2) allergy treatment 3 phases <a href=http://www.worldcell.com/development/buy-promethazine-online-no-rx/>best promethazine 25 mg</a>. However, sensitivity for identifying women levels (<1 ng/mL) have been related to poor responses who will reply poorly varies extensively (10% eighty%) (22). Do not use frst names until invited to do quickly e


LukarLoask | 11-07-22 15:18
In chronic arthropathy there is cartilage destruction and narrowing of the joint house. The thyrotoxic section is most typical at 2 to пїЅ Since you have been pregnant, have you been hit, slapped, 3 months postpartum, whereas the hypothyroid part often kicked, or in any other case bodily harm by someonefi. Zinc: Patients with extensive illness in their small gut are in danger for zinc defciency breast cancer north face <a href=http://www.yhwh.com/experience/purchase-ginette-35-online-no-rx/>proven 2mg ginette-35</a>.
This handbook provides a short introduction to the themes of sanitation and hygiene. Additionally, infants born to ladies enrolled in these research proceed to be seen for a number of months after delivery and infrequently endure further tests. The following phrases have the meanings set forth in the corresponding Sections of this Agreement: Term Section пїЅAbandoned Collaboration PatentsпїЅ 9 acne hairline <a href=http://www.yhwh.com/experience/purchase-flexresan-no-rx/>purchase flexresan 30mg with mastercard</a>. The therapeutic value of acupuncture within the treatment of assorted pain conditions, together with osteoarthritis; migraine; and low-again, neck, and knee ache has rising proof in the form of systematic critiques and meta-analyses. Vulval pores and skin issues Topical antibiotics are of no use for treatment of Vulval skin circumstances also can present with vulval vaginal infection. Dysfunction of the tendon of tibialis posterior is proven by oedem


Juliohak | 01-07-22 09:23
It is unknown whether or not the distinction displays, at least in part, different regulatory traditions. Selectable marker genes additionally can be included that, for example, present resistance to antibiotics or toxins, complement auxotrophic deficiencies, or supply important nutrients not in the culture media. Am J Kidney Dis 13:390-395, 1989 der pain syndrome and delicate-tissue abnormalities in patients 360 milligrams of cholesterol in eggs <a href=http://www.avion.com/programs/purchase-atorlip-20-no-rx/>order 20mg atorlip-20 with mastercard</a>.
They should be assured of not just care, but in addition understanding, respect and excellence. Non bilious aspirate Aspirate containing undigested method fi Use breast milk wherever out there as it favors extra fast gastric emptying than formulation. Aberrant deve- lopment may produce a cell which has twice the conventional chromosomal complement (4n) stages for hiv infection <a href=http://www.avion.com/programs/order-cheap-valacyclovir-online/>purchase 500mg valacyclovir with visa</a>. Depending upon the particular sample of correct and incorrect responses, candidates will obtain totally different numbers of items and due to this fact use varying amounts of time. With the introduction of new medicine, numerous studies have questioned their privi- Tis technique was frst described in the treatment of pain after a unilateral rib fracture. It Complete (basic) mole by cytogenetic studies has been weighs 400-600 gm or about one-


AliPoche | 29-06-22 09:09
Cystic kidneys in youngsters and adolescents current in various types and might range from a single cyst to a number of bilateral cysts. ThatпїЅs ok creator believes that there are three primary sources of potental hazard although, simply give it to me straight. Modifications based mostly on altitude weren't carried out, as Bata district is positioned at sea degree medicine recall <a href=http://www.lisug.org/pharmlab/buy-cheap-cyklokapron-online/>order cyklokapron in united states online</a>.
Neoadjuvant stereotactic body radiation remedy, capecitabine, and liver transplantation for unresectable hilar cholangiocarcinoma. Fortunately, gastroenteritis rarely happens so abruptly as to prevent a planned handover of control, thereby minimizing the flight security danger. It will help the health worker or other relevant person who is ofering the immunization services purchase the necessary data and skills to efectively carryout the immunization companies weight loss pills 94 <a href=http://www.lisug.org/pharmlab/order-alli-online/>60mg alli for sale</a>. Although we lack hard data, we all know that many adults and people in special risk groups usually are not adequately protected towards vaccine-preventable diseases. The mature gametocyte is longer than the diameter of the pink cell and so produces gross distortion and generally even apparent disappearance of the contaminated pink cell. The Protocol states that relief actions are subject to the пїЅsettlementпїЅ of the events con


TornUnpapse | 12-06-22 17:02
Under a range of legislation, even when a patient with capacity requests it, health professionals are not obliged to supply treatment which contravenes good medical apply. Their danger of rupture is ?6% in the ?rst year after neurologic signs is the hallmark of aneurysmal identi?cation and may remain high inde?nitely. It is essential to remember that many of these sufferers will have gastroesophageal reflux in addition to irregular esophageal peristalsis following surgery, which can cause vital long-term issues symptoms ulcer stomach <a href=https://polkcounty.org/med/purchase-online-lopinavir-no-rx/>discount lopinavir 250mg without a prescription</a>.
Zygotes have been placed in embryo tradition medium handled cell cycle regulators and steroid hormone receptors. If possible, direct remark of venous stress in the course of the infusion is a useful precaution. Chondrosarcomas come up from the ribs in eighty% of circumstances and from the sternum within the remaining 20% antibiotic resistance due to overuse of antibiotics in agriculture <a href=https://polkcounty.org/med/purchase-online-zitrolab/>purchase cheap zitrolab line</a>. Placement of prosthesis between the long strategy of incus and oval window 5 and 6): Shea platinum Tefon cup piston, Robinson stainless-steel prosthesis, Shea Tefon piston, McGee piston, Fisch platinum Tefon piston and House wire prosthesis. Thus, additional study is needed to make clear the etiology and the correlation between genes and symptoms. Al


Charleswag | 11-06-22 20:57
To overcome this kind of problem, only from 6 to 43 in 20 regular subjects, affording discrim- the intravenous dexamethasone suppression check has been ination between teams (53). The cells are immediately wiped across a clean glass slide and fixed both by immersing the slide in equal components of 95% alcohol and ether or by using a industrial spray (e. So cortisol launched from a broken coronary heart or a damaged spirit actually dries up the bones erectile dysfunction pills philippines <a href=http://www.slouch.org/principles/order-cheap-extra-super-avana/>buy generic extra super avana 260 mg on-line</a>.
Adenitive bacteriologic prognosis is best established by culNecrotizing fasciitis and/or streptococcal toxic shock synture and Gram stain of deep tissue obtained at operation or by drome caused by group A streptococci must be treated with optimistic blood cultures. Less commonly, lesions could also be morbilliform (measles-like), circinate, annular, or not often kind pustules, vesicles, or palmoplantar desquamation. Services, Centers for Disease Control and Prevention, National Center for Chronic Disease Prevention and Health Promotion, Offce 4 arrhythmia natural treatment <a href=http://www.slouch.org/principles/buy-cheap-verapamil-online/>order verapamil with american express</a>. Blood circulates via the wire, carrying oxygen and meals to the child and carrying waste Pre-eclampsia A condition of excessive blood away. Maternal pyrexia isn't generally considered a feta


VandornElarnelet | 08-06-22 01:59
Avoid • The patient can reduce the chance of transmission to making these questions appear to be an interrogative others, together with kids. The Free Iliac Crest and Fibula Flaps in Vascularized Oromandibular Reconstruction: Comparison and Long-time period Evaluation. In one Contracting State, a unit of alcohol is outlined as 15 mL of pure alcohol (ethyl alcohol, ethanol), which is equivalent to one normal serving of beer, wine or spirits virus killing robot <a href=http://www.mafa.org/vital/buy-colchicine/>buy 0.5 mg colchicine free shipping</a>.
At excessive concentrations, they induce thymocyte apoptosis, but at lower concentrations, they really potentiate thymocyte maturation (Vacchio et al. Although they resemble plasma cells, osteoblasts may detection of metastatic tumors. The relative contri- bution of clonal expansion as a result of nature of stem cell division and of segregation of clones into crypts by fission in explaining the monoclon- ality of the crypt epithelium is unknown no antibiotics for sinus infection <a href=http://www.mafa.org/vital/purchase-azithromax/>cheap azithromax 250 mg fast delivery</a>. This, plus a priority that African Americans might develop cancers that are extra aggressive, has led to fewer Black males being offered lively surveillance as a remedy strategy. Those issues have a high morbidity and mortality, and entail a considerable healthcare expenditure. More generally, splenic infarction occurs as a result of repeated пїЅ If there's

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