今天无聊,公布自己的写的一个函数,这个函数是我的蝈蝈采集系统的核心函数。通过这个函数,你可以把获取到的html代码按照你想要的部分提取出来。这个函数的特点是简单易用,不需要正则。有了这个函数你也可以写采集程序了!哈哈!
代码如下:
<?
/*
* 作者:askie
* 主页:http://www.pkphp.com
* email or gtalk: imaskie[at]gmail.com
*
* $str:任意字符串
* $start:要替取的字符串之前的字符串
* $end:要替取的字符串之前的字符串
* $add:提取出来的结果是否加上$start和$end
* 返回数组
*/
function inContent($str,$start,$end,$add=true)
{
$first=strstr($str,$start);
if ($first==false)
{
return array();
}
else
{
$first=substr($first,strlen($start));
}
$second=strstr($first,$end);
if ($second==false)
{
if ($add)
{
return array($start.$first);
}
else
{
return array($first);
}
}
$final=substr($first,0,-strlen($second));
if ($add)
{
$final=$start.$final.$end;
}
$result[]=$final;
$second=substr($second,strlen($end));
if (strstr($second,$start))
{
$result=array_merge($result,inContent(substr($second,strlen($end)),$start,$end,$add));
}
return $result;
}
//例子
$html='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en-US">
<head profile="http://gmpg.org/xfn/11">
<title>记录与PHP的PK经历 / PK with php!</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" media="screen,projection" href="http://www.pkphp.com/wp-content/themes/plaintxtblog/style.css" title="plaintxtBlog" />
<link rel="stylesheet" type="text/css" media="print" href="http://www.pkphp.com/wp-content/themes/plaintxtblog/print.css" />
<link rel="alternate" type="application/rss+xml" href="http://www.pkphp.com/feed/" title="记录与PHP的PK经历 RSS feed" />
<link rel="alternate" type="application/rss+xml" href="http://www.pkphp.com/comments/feed/" title="记录与PHP的PK经历 comments RSS feed" />
<link rel="pingback" href="http://www.pkphp.com/xmlrpc.php" />
';
//获取title
print_r(inContent($html,'<title>','</title>',false));
/*
返回:
Array
(
[0] => 记录与PHP的PK经历 / PK with php!
)
*/
print_r(inContent($html,'<title>','</title>',true));
/*
返回:
Array
(
[0] => <title>记录与PHP的PK经历 / PK with php!</title>
)
*/
print_r(inContent($html,'href="','"',false));
/*
返回:
Array
(
[0] => http://www.pkphp.com/wp-content/themes/plaintxtblog/style.css
[1] => http://www.pkphp.com/wp-content/themes/plaintxtblog/print.css
[2] => http://www.pkphp.com/feed/
[3] => http://www.pkphp.com/comments/feed/
[4] => http://www.pkphp.com/xmlrpc.php
)
*/
?>
这个函数对你有用么?

2 Comments
你的采集程序现在好像下不了了啊。
恩,代码丢失了!
Post a Comment