用户
 找回密码
 入住 CI 中国社区
搜索
查看: 5296|回复: 1
收起左侧

php编写自定义样式的搜索引擎

[复制链接]
发表于 2008-2-26 11:52:47 | 显示全部楼层 |阅读模式
    刚开始学php,做个小例子同初学者共同学习,讨论:
       程序要求:在Google中搜索关键字,将搜索结果的标题、网址和简介取出,改成自已喜欢和需要的样式。
       程序步骤:首先,去除Google搜索结果的台头和脚注,在剩余的搜索结果中再分割出各项小条目,再从小条目中剥离HTML格式标记,替换成我们想要的格式。
<?php
$keywords=$_GET['keywords'];

echo '<form method="get">'; //没有参数的form,默认提交方式为get,提交到本身
echo '<input type="text" name="keywords">'; //构造一个文本输入框
echo '<input type="submit" value="查询">'; //构造一个提交查询按钮
echo '</form>';

if (isset($keywords)) //提交后PHP会生成变量 kwywords,即要求下面的程序在提交后运行
{
urlencode($keywords); //对用户输入内容进行URL编码
$result=file("http://www.google.com/search?q=". $keywords."&btnG=Google%CB%D1%CB%F7&hl=zh-CN&lr="); //对查询语句进行变量替换,将查询结果保存在数组变量 result中
$result_string=join('',$result);  //将数组$result合并成字符串,各数组元素之间用空格粘和
//echo $result_string;
$result_string=strstr($result_string,"<div><div class=g>");//去掉台头;

$position=strpos($result_string,"<p class=e>");
$result_string=substr($result_string,0, $position);//截取第一个

//我们就得到一个数组 result_array,其中每个元素都是一个搜索结果条目。我们所要做的仅仅是研究每个条目及其HTML显示格式代码,然后按要求替换就行了。下面用循环来处理 result_array中的每个条目。
$result_array=explode("</td></tr></table></div>" ,$result_string); //分割小条目;

for($i=0;$i<3;$i++){
        //除掉红色样式
  $styleT="<font color=CC0033>";
  $styleE="</font>";
  $result_array[$i]=ereg_replace($styleT,"",$result_array[$i]);
  $result_array[$i]=ereg_replace($styleE,"",$result_array[$i]);
  //echo $result_array[$i];
  
     //取出标题
  $titleT=".+class=l>";
  $titleE="</a>.+";
  $title[$i]=ereg_replace($titleT,"",$result_array[$i]);
  $title[$i]=ereg_replace($titleE,"",$title[$i]);
  echo $title[$i];
   
  //取出内容提要
  echo "<br/>";
  $c;
  $c;
  $content[$i]=ereg_replace($contentT,"",$result_array[$i]);
  $content[$i]=ereg_replace($contentE,"",$content[$i]);
  echo $content[$i];
  
  //取出链接
     $urlleft=".+<a href=\"";
  $urlright="\" target=_blank.+";
        $urll=ereg_replace($urlleft,"",$result_array[$i]);
  $url=ereg_replace($urlright,"",$urll);
  echo $url;
  echo "<br/>";
      
  }
  
  }
?>

//这样我们就得出一个完全没有样式的搜索结果啦,大家可根据自己的需求另加样式。



[ 本帖最后由 vavalen 于 2008-2-26 12:07 编辑 ]

评分

参与人数 1威望 +5 收起 理由
Hex + 5 原创内容

查看全部评分

发表于 2008-2-26 12:17:25 | 显示全部楼层
支持美女程序员~~~~~~~~

本版积分规则