Home > php教程 > php手册 > php站内搜索关键词变亮方法

php站内搜索关键词变亮方法

WBOY
Release: 2016-05-25 16:38:25
Original
1204 people have browsed it

我们这个做法是把搜索结果出来,与搜索关键词相同的替换成高亮的字, 我们会用到str_replace(你找的关键字,你找的关键字,$str); 

就这么容易了,好了下面我们来看一个实例吧.

先创建一个数据库:create database 'searchKey';

再创建表,SQL建库代码如下:

CREATE TABLE `fangke_cc`.`search` ( 
`id` INT( 4 ) NOT NULL AUTO_INCREMENT , 
`keyword` VARCHAR( 20 ) NOT NULL , 
PRIMARY KEY ( `id` )  
) ENGINE = MYISAM
Copy after login

我们导入一些数据,SQL建库代码如下:

INSERT INTO `search` (`id`, `keyword`) VALUES 
(1, '中国WEB第一站www.phprm.com'), 
(2, '中国WEB第一站www.phprm.com'), 
(3, '中国WEB第一站www.phprm.com'), 
(4, '中国WEB第一站www.phprm.com');
Copy after login

好了下面我们就来执行查询操作,实例代码如下:

<?php
if ($_POST) {
    $db = &#39;fangke_cc&#39;;
    mysql_pconnect(&#39;localhost&#39;, &#39;root&#39;, &#39;root&#39;) or die(mysql_error());
    mysql_select_db($db);
    mysql_query("set names &#39;gbk&#39;");
    $key = $_POST[&#39;keyword&#39;];
    $sql = "Select * from search where keyword like &#39;%$key%&#39;";
    $query = mysql_query($sql);
    while ($rs = mysql_fetch_array($query)) {
        echo str_replace($key, "<b>$key</b>", $rs[&#39;keyword&#39;]) , &#39;<br />&#39;;
    }
    /*
    中国WEB第一站www.<b>phprm</b>.com<br />
    中国WEB第一站www.<b>phprm</b>.com<br />
    中国WEB第一站www.<b>phprm</b>.com<br />
    中国WEB第一站
    */
}
?> 
<form name="form1" method="post" action=""> 
  <label> 
  <input name="keyword" type="text" id="keyword"> 
  </label> 
  <label> 
  <input type="submit" name="Submit" value="提交"> 
  </label> 
</form>
Copy after login


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template