Дабы не создавать тему с таким же названием, решил написАть тут.
Прошу совета в следующем вопросе: осуществляю поиск по одной таблице в одной БД, поиск ведется по двум столбцам (код и комментарий). В качестве "движка" выбран достаточно распространенный готовый скрипт, слегка доработанный и подогнанный под стиль сайта.
Окончательный (на сегодняшний день) вариант представляю ниже:
PHP:
<?
include 'opendb.php';
$connections = mysql_connect($hostname_logon, $username_logon, $password_logon) or die ( "Unabale to connect to the database" );
//select database
mysql_select_db($database_logon) or die ( "Unable to select database!" );
//specify how many results to display per page
$limit = 30;
// Get the search variable from URL
$var = @$_GET['q'] ;
//trim whitespace from the stored variable
$trimmed = trim($var);
//separate key-phrases into keywords
$trimmed_array = explode(" ",$trimmed);
$trimmed = preg_replace("/[^\w\x7F-\xFF\s]/", " ", $trimmed);
$good = trim(preg_replace("/\s(\S{1,3})\s/", " ", ereg_replace(" +", " "," $trimmed ")));
$good = ereg_replace(" +", " ", $good);
// check for an empty string and display a message.
if ($good == "") { $resultmsg = "<span class=error>Код слишком короткий! Введите <strong>минимум четыре</strong> символа!</span>" ; }
// check for a search parameter
if (!isset($var)){ $resultmsg = "<span class=error>Пожалуйста, введите код детали (минимум <strong>четыре</strong> символа).</span>" ; }
// Build SQL Query for each keyword entered
foreach ($trimmed_array as $trimm){
// EDIT HERE and specify your table and field names for the SQL query
$query = "SELECT * FROM export_new WHERE code LIKE \"%$trimm%\" || comm LIKE \"%$trimm%\" ORDER BY code" ;
// Execute the query to get number of rows that contain search kewords
$numresults=mysql_query ($query);
$row_num_links_main =mysql_num_rows ($numresults);
// next determine if 's' has been passed to script, if not use 0.
// 's' is a variable that gets set as we navigate the search result pages.
if (empty($s)) {
$s=0;
}
// now let's get results.
$query .= " LIMIT $s,$limit" ;
$numresults = mysql_query ($query) or die ( "Couldn't execute query" );
$row= mysql_fetch_array ($numresults);
//store record id of every item that contains the keyword in the array we need to do this to avoid display of duplicate search result.
do{
//EDIT HERE and specify your field name that is primary key
$adid_array[] = $row[ 'code' ];
}
while( $row= mysql_fetch_array($numresults)); }
//end foreach
if($row_num_links_main == 0 && $row_set_num == 0){
$resultmsg = "<div align=left class=result><img align=middle border=0 alt=net v nalichii src=../images/search/00.png> - К сожалению, по Вашему запросу <strong>".$good."</strong> ничего не найдено.</div>";
}
//delete duplicate record id's from the array. To do this we will use array_unique function
$tmparr = array_unique($adid_array);
$i=0;
foreach ($tmparr as $v) {
$newarr[$i] = $v;
$i++;
}
// now you can display the results returned. But first we will display the search form on the top of the page
?>
<form action="search.php" method="get" name="search">
<div align="center">
<input class="inputbox" name="q" type="text" value="<?php echo $q; ?>" size="20" maxlength="25">
<input class="button" name="search" type="submit" value="Поиск">
</div>
</form>
<?php
// display what the person searched for.
if( isset ($resultmsg)){
echo $resultmsg;
exit();
}
if ($row_num_links_main > 30) {
echo "<span class=comm>Найдено более <strong>30</strong> значений.<br />Повторите поиск с более точным номером детали.</span>";
exit(); }
else{
echo "<br /><div align=center class=result><strong>Условные обозначения:</strong></div>";
echo "<div align=left class=comm>";
echo "<img align=middle border=0 alt=net_v_nalichii src=../images/search/00.png> - <strong>сегодня нет</strong> в наличии<br />";
echo "<img align=middle border=0 alt=bolee_10 src=../images/search/22.png> - имеется в количестве <strong>10 единиц или более</strong><br />";
echo "<img align=middle border=0 alt=menee_10 src=../images/search/11.png> - имеется в количестве <strong>менее 10 единиц</strong><br /><br /></div>";
echo "
<div align=center>
<table class=result width=100% height=100% border=1 cellspacing=0 cellpadding=0>
<tr>
<td class=heads>Код</td>
<td class=heads>Описание</td>
<td class=heads>Цена</td>
<td class=heads>Наличие</td>
</tr>";
}
foreach($newarr as $value){
// EDIT HERE and specify your table and field names for the SQL query
$query_value = "SELECT * FROM export_new WHERE code = '$value'";
$num_value=mysql_query ($query_value);
$row_linkcat= mysql_fetch_array ($num_value);
$row_num_links= mysql_num_rows ($num_value);
//now let's make the keywods bold. To do that we will use preg_replace function.
//EDIT parts of the lines below that have fields names like $row_linkcat[ '' ]
$titlehigh = preg_replace ( "'($var)'si" , "<span style=background-color:#FFAAAA;font-weight:bold>\\1</span>" , $row_linkcat[ 'comm' ] );
$linkhigh = preg_replace ( "'($var)'si" , "<span style=background-color:#FFAAAA;font-weight:bold>\\1</span>" , $row_linkcat[ 'code' ] );
$linkdesc = preg_replace ( "'($var)'si" , "<span style=background-color:#CCCCFF;font-weight:bold>\\1</span>" , $row_linkcat[ 'price' ] );
$linkq = preg_replace ( "'($var)'si" , "<span style=background-color:#CCCCFF;font-weight:bold>\\1</span>" , $row_linkcat[ 'q' ] );
foreach($trimmed_array as $trimm){
if($trimm != 'b' ){
//IF you added more fields to search make sure to add them below as well.
// $titlehigh = preg_replace( "'($trimm)'si" , "<b>\\1</b>" , $titlehigh);
//$linkhigh = preg_replace( "'($trimm)'si" , "<b>\\1</b>" , $linkhigh);
//$linkdesc = preg_replace( "'($trimm)'si" , "<b>\\1</b>" , $linkdesc);
}
//end highlight
if ($linkq == 0) {
$linkq = "<img border=0 width=8px height=8px alt=net v nalichii src=../images/search/0.png>";
}
if ($linkq == 1) {
$linkq = "<img border=0 width=8px height=8px alt=net v nalichii src=../images/search/1.png>";
}
if ($linkq == 2) {
$linkq = "<img border=0 width=8px height=8px alt=net v nalichii src=../images/search/2.png>";
}
?>
<tr>
<td><strong><?php echo $linkhigh; ?></strong></td>
<td><?php echo $titlehigh; ?></td>
<td><strong><?php echo $linkdesc; ?></strong></td>
<td><?php echo $linkq; ?></td>
</tr>
<?php
}
}
echo "</table></div><br />";
echo $row_num_links_main."<div align=center>";
//end foreach $trimmed_array
if($row_num_links_main > $limit)
{
if ($s >= 1)
{
$prevs=($s-$limit);
echo "<a class=result href='$PHP_SELF?s=$prevs&q=$var&catid=$catid'><img border=0 width=17px height=7px alt=prev src=../images/search/prev.png></a>";
}
echo "<span class=result> <strong>Навигация</strong> </span>";
// check to see if last
$slimit =$s+$limit;
if (!($slimit >= $row_num_links_main) && $row_num_links_main!=1)
{
// not last page so display next link
$n=$s+$limit;
echo "<a class=result href='$PHP_SELF?s=$n&q=$var&catid=$catid'><img border=0 width=17px height=7px alt=next src=../images/search/next.png></a>";
}
}
echo "</div>";
?>
Дело в том, что при поиске слов с символом "
+" вываливаются уорнинги и никаких результатов поиска... :
Warning: preg_replace(): Compilation failed: nothing to repeat at offset 1 in ***\search\search.php on line 193
Warning: preg_replace(): Compilation failed: nothing to repeat at offset 1 in ***\search\search.php on line 194
Warning: preg_replace(): Compilation failed: nothing to repeat at offset 1 in ***\search\search.php on line 195
Warning: preg_replace(): Compilation failed: nothing to repeat at offset 1 in ***\search\search.php on line 196
вот эти строки:
$titlehigh = preg_replace ( "'($var)'si" , "<span style=background-color:#FFAAAA;font-weight:bold>\\1</span>" , $row_linkcat[ 'comm' ] );
$linkhigh = preg_replace ( "'($var)'si" , "<span style=background-color:#FFAAAA;font-weight:bold>\\1</span>" , $row_linkcat[ 'code' ] );
$linkdesc = preg_replace ( "'($var)'si" , "<span style=background-color:#CCCCFF;font-weight:bold>\\1</span>" , $row_linkcat[ 'price' ] );
$linkq = preg_replace ( "'($var)'si" , "<span style=background-color:#CCCCFF;font-weight:bold>\\1</span>" , $row_linkcat[ 'q' ] );
Когда я вместо
preg_replace ( "'($var)'si" , "<span ...
вставляю
preg_replace ( "'(
%$var
%)'si" , "<span ...
уорнинги исчезают и поиск осуществляется без проблем, но правда пропала подсветка кода в результатах поиска.
Подскажите, пожалуйста, как же все-таки осуществить поиск слов с "плюсом" ?
Заранее благодарен.