PHP代码片段记录:+多线程抓取网页等

来源:互联网 发布:广州数控车床仿真软件 编辑:程序博客网 时间:2024/05/16 03:13

来源:http://blog.donews.com/jiji262/2011/10/php代码片段记录-多线程抓取网页等

1.Discuz的PHP可逆加密解密函数

<?php
/**
*
* @param string $string 原文或者密文
* @param string $operation 操作(ENCODE | DECODE), 默认为 DECODE
* @param string $key 密钥
* @param int $expiry 密文有效期, 加密时候有效, 单位 秒,0 为永久有效
* @return string 处理后的 原文或者 经过 base64_encode 处理后的密文
* @example
*   $a = authcode(‘abc’, ‘ENCODE’, ‘key’);
*   $b = authcode($a, ‘DECODE’, ‘key’);  // $b(abc)
*
*   $a = authcode(‘abc’, ‘ENCODE’, ‘key’, 3600);
*   $b = authcode(‘abc’, ‘DECODE’, ‘key’); // 在一个小时内,$b(abc),否则 $b 为空
*/

function authcode($string, $operation = ‘DECODE’, $key = , $expiry = 0) {

$ckey_length = 4;

$key = md5($key ? $key : “kalvin.cn”);
$keya = md5(substr($key, 0, 16));
$keyb = md5(substr($key, 16, 16));
$keyc = $ckey_length ? ($operation == ‘DECODE’ ? substr($string, 0, $ckey_length):substr(md5(microtime()), -$ckey_length)) : ;

$cryptkey = $keya.md5($keya.$keyc);
$key_length = strlen($cryptkey);

$string = $operation == ‘DECODE’ ? base64_decode(substr($string, $ckey_length)) : sprintf(‘%010d’,$expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
$string_length = strlen($string);

$result = ;
$box = range(0, 255);

$rndkey = array();
for($i = 0; $i <= 255; $i++) {
$rndkey[$i] = ord($cryptkey[$i % $key_length]);
}

for($j = $i = 0; $i < 256; $i++) {
$j = ($j + $box[$i] + $rndkey[$i]) % 256;
$tmp = $box[$i];
$box[$i] = $box[$j];
$box[$j] = $tmp;
}

for($a = $j = $i = 0; $i < $string_length; $i++) {
$a = ($a + 1) % 256;
$j = ($j + $box[$a]) % 256;
$tmp = $box[$a];
$box[$a] = $box[$j];
$box[$j] = $tmp;
$result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
}

if($operation == ‘DECODE’) {
if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) ==substr(md5(substr($result, 26).$keyb), 0, 16)) {
return substr($result, 26);
} else {
return ;
}
} else {
return $keyc.str_replace(‘=’, , base64_encode($result));
}

}
?>

2.PHP通过API获取新浪短网址函数

function sinaurl($url, $key = ‘1335371408′) {
$opts['http'] = array(‘method’ => “GET”, ‘timeout’=>60,);
$context = stream_context_create($opts);
$url = “http://api.t.sina.com.cn/short_url/shorten.json?source=$key&url_long=$url;
$html = @file_get_contents($url,false,$context);
$url = json_decode($html,true);
if (!empty($url[0]['url_short'])) {
return $url[0]['url_short'];
}
}

3.PHP CURL_MULTI 多线程采集网页函数

<?php
$text = remote(array(‘http://www.kalvin.cn/about-me/’,‘http://www.kalvin.cn/’));
print_r($text);

function remote($urls) {
if (!is_array($urls) or count($urls) == 0) {
return false;
}

$curl = $text = array();
$handle = curl_multi_init();
foreach($urls as $k => $v) {
$nurl[$k]= preg_replace(‘~([^:\/\.]+)~ei’, “rawurlencode(‘\\1′)”, $v);
$curl[$k] = curl_init($nurl[$k]);
curl_setopt($curl[$k], CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl[$k], CURLOPT_HEADER, 0);
curl_multi_add_handle ($handle, $curl[$k]);
}

$active = null;
do {
$mrc = curl_multi_exec($handle, $active);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);

while ($active && $mrc == CURLM_OK) {
if (curl_multi_select($handle) != -1) {
do {
$mrc = curl_multi_exec($handle, $active);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);
}
}

foreach ($curl as $k => $v) {
if (curl_error($curl[$k]) == “”) {
$text[$k] = (string) curl_multi_getcontent($curl[$k]);
}
curl_multi_remove_handle($handle, $curl[$k]);
curl_close($curl[$k]);
}
curl_multi_close($handle);
return $text;
}

4.PHP版Bing翻译API函数,支持自动识别语言

function bingtrans($string, $from = ‘-’, $to = ‘en’, $key = ) {
$from = $from != “-” ? $from : “”;
$opts['http'] = array(‘method’ => “POST”, ‘content’ => $string, ‘timeout’=>60,);
$context = stream_context_create($opts);
$url = “http://api.microsofttranslator.com/V1/Http.svc/Translate?appId=$key&from=$from&to=$to&contentType=text%2Fhtml”;
$html = preg_replace(‘/^(\xef\xbb\xbf)/’, , @file_get_contents($url,false,$context));
if (!empty($html)) {
return $html;
}
}

使用前请先到Bing Developer Center去申请一个ApiId;

5. PHP解密Unicode及Escape加密字符串函数

<?php
function uni_decode($s) {
preg_match_all(‘/\&\#([0-9]{2,5})\;/’, $s, $html_uni);
preg_match_all(‘/[\\\%]u([0-9a-f]{4})/ie’, $s, $js_uni);
$source = array_merge($html_uni[0], $js_uni[0]);
$js = array();
for($i=0;$i<count($js_uni[1]);$i++) {
$js[] = hexdec($js_uni[1][$i]);
}
$utf8 = array_merge($html_uni[1], $js);
$code = $s;
for($j=0;$j<count($utf8);$j++) {
$code = str_replace($source[$j], unicode2utf8($utf8[$j]), $code);
}
return $code;//$s;//preg_replace(‘/\\\u([0-9a-f]{4})/ie’, “chr(hexdec(‘\\1′))”,  $s); 
}

function unicode2utf8($c) {
$str=“”;
if ($c < 0×80) {
$str.=chr($c);
} else if ($c < 0×800) {
$str.=chr(0xc0 | $c>>6);
$str.=chr(0×80 | $c & 0×3f);
} else if ($c < 0×10000) {
$str.=chr(0xe0 | $c>>12);
$str.=chr(0×80 | $c>>6 & 0×3f);
$str.=chr(0×80 | $c & 0×3f);
} else if ($c < 0×200000) {
$str.=chr(0xf0 | $c>>18);
$str.=chr(0×80 | $c>>12 & 0×3f);
$str.=chr(0×80 | $c>>6 & 0×3f);
$str.=chr(0×80 | $c & 0×3f);
}
return $str;
}

$str=‘%u5927%u5BB6%u597D%uFF0C我是孤魂!<br />\u8FD9\u662F\u6D4B\u8BD5\u6587\u672C\uFF01′;
echo uni_decode($str); // 大家好,我是孤魂!这是测试文本! 
?>

6.PHP生成缩略图函数

function img_create_small($big_img, $width, $height, $small_img) { // 大图文件地址,缩略宽,缩略高,小图地址
$imgage = getimagesize($big_img); //获取大图信息 
switch ($imgage[2]) { // 判断图像类型 
case 1:
$im = imagecreatefromgif($big_img);
break;
case 2:
$im = imagecreatefromjpeg($big_img);
break;
case 3:
$im = imagecreatefrompng($big_img);
break;
}
$src_W = $imgage[0]; //获取大图宽 
$src_H = $imgage[1]; //获取大图高 
$tn = imagecreatetruecolor($width, $height); //创建小图 
imagecopyresampled($tn, $im, 0, 0, 0, 0, $width, $height, $src_W, $src_H); //复制图像并改变大小 
imagejpeg($tn, $small_img); //输出图像 
}

7.正则表达式匹配标点符号

<?php
$value = “123~!@#$%^&*()_+<>?:,./;’,。、‘:“《》?~!@#¥%……()”;
preg_replace(“~(\s+|[\\pP])~i”,“-”,$value);
?>

上面是实例,简单的说就是 [\\pP] 这几个字符串了,可以匹配任何全角或半角的标点符号,参考上面的例子可以得出结果。Unicode 编码并不只是为某个字符简单定义了一个编码,而且还将其进行了归类。

\pP 其中的小写 p 是 property 的意思,表示 Unicode 属性,用于 Unicode 正表达式的前缀。
大写 P 表示 Unicode 字符集七个字符属性之一:标点字符。

其他六个是
L:字母;
M:标记符号(一般不会单独出现);
Z:分隔符(比如空格、换行等);
S:符号(比如数学符号、货币符号等);
N:数字(比如阿拉伯数字、罗马数字等);
C:其他字符

8.常用PHP正则表达式

获取所有图片网址preg_match_all(“/ src=(\”|\’){0,}(http:\/\/(.+?))(\”|\’|\s|>)/is”,$text,$img);

匹配中文字符的正则表达式: [\u4e00-\u9fa5]
匹配双字节字符(包括汉字在内):[^\x00-\xff]
匹配空行的正则表达式:\n[\s| ]*\r
匹配HTML标记的正则表达式:/<(.*)>.*<\/\1>|<(.*) \/>/
匹配首尾空格的正则表达式:(^\s*)|(\s*$)
匹配Email地址的正则表达式:\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*
匹配网址URL的正则表达式:^[a-zA-z]+://(\\w+(-\\w+)*)(\\.(\\w+(-\\w+)*))*(\\?\\S*)?$
匹配帐号是否合法(字母开头,允许5-16字节,允许字母数字下划线):^[a-zA-Z][a-zA-Z0-9_]{4,15}$
匹配国内电话号码:(\d{3}-|\d{4}-)?(\d{8}|\d{7})?
匹配腾讯QQ号:^[1-9]*[1-9][0-9]*$<span id=”more-58″></span>
“^\d+$”  //非负整数(正整数 + 0)
“^[0-9]*[1-9][0-9]*$”  //正整数
“^((-\d+)|(0+))$”  //非正整数(负整数 + 0)
“^-[0-9]*[1-9][0-9]*$”  //负整数
“^-?\d+$”    //整数
“^\d+(\.\d+)?$”  //非负浮点数(正浮点数 + 0)
“^(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*))$”  //正浮点数
“^((-\d+(\.\d+)?)|(0+(\.0+)?))$”  //非正浮点数(负浮点数 + 0)
“^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$”  //负浮点数
“^(-?\d+)(\.\d+)?$”  //浮点数
“^[A-Za-z]+$”  //由26个英文字母组成的字符串
“^[A-Z]+$”  //由26个英文字母的大写组成的字符串
“^[a-z]+$”  //由26个英文字母的小写组成的字符串
“^[A-Za-z0-9]+$”  //由数字和26个英文字母组成的字符串
“^\w+$”  //由数字、26个英文字母或者下划线组成的字符串
“^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$”    //email地址
“^[a-zA-z]+://(\w+(-\w+)*)(\.(\w+(-\w+)*))*(\?\S*)?$”  //url
/^(d{2}|d{4})-((0([1-9]{1}))|(1[1|2]))-(([0-2]([1-9]{1}))|(3[0|1]))$/   //  年-月-日
/^((0([1-9]{1}))|(1[1|2]))/(([0-2]([1-9]{1}))|(3[0|1]))/(d{2}|d{4})$/   // 月/日/年
“^([w-.]+)@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.)|(([w-]+.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(]?)$”   //Emil
/^((\+?[0-9]{2,4}\-[0-9]{3,4}\-)|([0-9]{3,4}\-))?([0-9]{7,8})(\-[0-9]+)?$/     //电话号码
“^(d{1,2}|1dd|2[0-4]d|25[0-5]).(d{1,2}|1dd|2[0-4]d|25[0-5]).(d{1,2}|1dd|2[0-4]d|25[0-5]).(d{1,2}|1dd|2[0-4]d|25[0-5])$”   //IP地址

元字符及其在正则表达式上下文中的行为:

\ 将下一个字符标记为一个特殊字符、或一个原义字符、或一个后向引用、或一个八进制转义符。

^ 匹配输入字符串的开始位置。如果设置了 RegExp 对象的Multiline 属性,^ 也匹配 ’\n’ 或 ’\r’ 之后的位置。

$ 匹配输入字符串的结束位置。如果设置了 RegExp 对象的Multiline 属性,$ 也匹配 ’\n’ 或 ’\r’ 之前的位置。

* 匹配前面的子表达式零次或多次。

+ 匹配前面的子表达式一次或多次。+ 等价于 {1,}。

? 匹配前面的子表达式零次或一次。? 等价于 {0,1}。

{n} n 是一个非负整数,匹配确定的n 次。

{n,} n 是一个非负整数,至少匹配n 次。

{n,m} m 和 n 均为非负整数,其中n <= m。最少匹配 n 次且最多匹配 m 次。在逗号和两个数之间不能有空格。

? 当该字符紧跟在任何一个其他限制符 (*, +, ?, {n}, {n,}, {n,m}) 后面时,匹配模式是非贪婪的。非贪婪模式尽可能少的匹配所搜索的字符串,而默认的贪婪模式则尽可能多的匹配所搜索的字符串。

. 匹配除 “\n” 之外的任何单个字符。要匹配包括 ’\n’ 在内的任何字符,请使用象 ’[.\n]’ 的模式。
(pattern) 匹配pattern 并获取这一匹配。

(?:pattern) 匹配pattern 但不获取匹配结果,也就是说这是一个非获取匹配,不进行存储供以后使用。

(?=pattern) 正向预查,在任何匹配 pattern 的字符串开始处匹配查找字符串。这是一个非获取匹配,也就是说,该匹配不需要获取供以后使用。

(?!pattern) 负向预查,与(?=pattern)作用相反

x|y 匹配 x 或 y。

[xyz] 字符集合。

[^xyz] 负值字符集合。

[a-z] 字符范围,匹配指定范围内的任意字符。

[^a-z] 负值字符范围,匹配任何不在指定范围内的任意字符。

\b 匹配一个单词边界,也就是指单词和空格间的位置。

\B 匹配非单词边界。

\cx 匹配由x指明的控制字符。

\d 匹配一个数字字符。等价于 [0-9]。

\D 匹配一个非数字字符。等价于 [^0-9]。

\f 匹配一个换页符。等价于 \x0c 和 \cL。

\n 匹配一个换行符。等价于 \x0a 和 \cJ。

\r 匹配一个回车符。等价于 \x0d 和 \cM。

\s 匹配任何空白字符,包括空格、制表符、换页符等等。等价于[ \f\n\r\t\v]。

\S 匹配任何非空白字符。等价于 [^ \f\n\r\t\v]。

\t 匹配一个制表符。等价于 \x09 和 \cI。

\v 匹配一个垂直制表符。等价于 \x0b 和 \cK。

\w 匹配包括下划线的任何单词字符。等价于’[A-Za-z0-9_]’。

\W 匹配任何非单词字符。等价于 ’[^A-Za-z0-9_]’。

\xn 匹配 n,其中 n 为十六进制转义值。十六进制转义值必须为确定的两个数字长。

\num 匹配 num,其中num是一个正整数。对所获取的匹配的引用。

\n 标识一个八进制转义值或一个后向引用。如果 \n 之前至少 n 个获取的子表达式,则 n 为后向引用。否则,如果 n 为八进制数字 (0-7),则 n 为一个八进制转义值。

\nm 标识一个八进制转义值或一个后向引用。如果 \nm 之前至少有is preceded by at least nm 个获取得子表达式,则 nm 为后向引用。如果 \nm 之前至少有 n 个获取,则 n 为一个后跟文字 m 的后向引用。如果前面的条件都不满足,若 n 和 m 均为八进制数字 (0-7),则 \nm 将匹配八进制转义值 nm。

\nml 如果 n 为八进制数字 (0-3),且 m 和 l 均为八进制数字 (0-7),则匹配八进制转义值 nml。

\un 匹配 n,其中 n 是一个用四个十六进制数字表示的Unicode字符。

匹配中文字符的正则表达式: [u4e00-u9fa5]

匹配双字节字符(包括汉字在内):[^x00-xff]

匹配空行的正则表达式:n[s| ]*r

匹配HTML标记的正则表达式:/<(.*)>.*</1>|<(.*) />/

匹配首尾空格的正则表达式:(^s*)|(s*$)

匹配Email地址的正则表达式:w+([-+.]w+)*@w+([-.]w+)*.w+([-.]w+)*

匹配网址URL的正则表达式:http://([w-]+.)+[w-]+(/[w- ./?%&=]*)?

利用正则表达式限制网页表单里的文本框输入内容:

用正则表达式限制只能输入中文:onkeyup=”value=value.replace(/[^u4E00-u9FA5]/g,”)” onbeforepaste=”clipboardData.setData(‘text’,clipboardData.getData(‘text’).replace(/[^u4E00-u9FA5]/g,”))”

用正则表达式限制只能输入全角字符: onkeyup=”value=value.replace(/[^uFF00-uFFFF]/g,”)” onbeforepaste=”clipboardData.setData(‘text’,clipboardData.getData(‘text’).replace(/[^uFF00-uFFFF]/g,”))”

用正则表达式限制只能输入数字:onkeyup=”value=value.replace(/[^d]/g,”) “onbeforepaste=”clipboardData.setData(‘text’,clipboardData.getData(‘text’).replace(/[^d]/g,”))”

用正则表达式限制只能输入数字和英文:onkeyup=”value=value.replace(/[W]/g,”) “onbeforepaste=”clipboardData.setData(‘text’,clipboardData.getData(‘text’).replace(/[^d]/g,”))”

=========常用正则式

匹配中文字符的正则表达式: [\u4e00-\u9fa5]

匹配双字节字符(包括汉字在内):[^\x00-\xff]

匹配空行的正则表达式:\n[\s| ]*\r

匹配HTML标记的正则表达式:/<(.*)>.*<\/\1>|<(.*) \/>/

匹配首尾空格的正则表达式:(^\s*)|(\s*$)

匹配IP地址的正则表达式:/(\d+)\.(\d+)\.(\d+)\.(\d+)/g //

匹配Email地址的正则表达式:\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*

匹配网址URL的正则表达式:http://(/[\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?

sql语句:^(select|drop|delete|create|update|insert).*$

1、非负整数:^\d+$

2、正整数:^[0-9]*[1-9][0-9]*$

3、非正整数:^((-\d+)|(0+))$

4、负整数:^-[0-9]*[1-9][0-9]*$

5、整数:^-?\d+$

6、非负浮点数:^\d+(\.\d+)?$

7、正浮点数:^((0-9)+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*))$

8、非正浮点数:^((-\d+\.\d+)?)|(0+(\.0+)?))$

9、负浮点数:^(-((正浮点数正则式)))$

10、英文字符串:^[A-Za-z]+$

11、英文大写串:^[A-Z]+$

12、英文小写串:^[a-z]+$

13、英文字符数字串:^[A-Za-z0-9]+$

14、英数字加下划线串:^\w+$

15、E-mail地址:^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$

16、URL:^[a-zA-Z]+://(\w+(-\w+)*)(\.(\w+(-\w+)*))*(\?\s*)?$
或:^http:\/\/[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\’:+!]*([^<>\"\"])*$

17、邮政编码:^[1-9]\d{5}$

18、中文:^[\u0391-\uFFE5]+$

19、电话号码:^((\(\d{2,3}\))|(\d{3}\-))?(\(0\d{2,3}\)|0\d{2,3}-)?[1-9]\d{6,7}(\-\d{1,4})?$

20、手机号码:^((\(\d{2,3}\))|(\d{3}\-))?13\d{9}$

21、双字节字符(包括汉字在内):^\x00-\xff

22、匹配首尾空格:(^\s*)|(\s*$)(像vbscript那样的trim函数)

23、匹配HTML标记:<(.*)>.*<\/\1>|<(.*) \/>

24、匹配空行:\n[\s| ]*\r

25、提取信息中的网络链接:(h|H)(r|R)(e|E)(f|F) *= *(‘|”)?(\w|\\|\/|\.)+(‘|”| *|>)?

26、提取信息中的邮件地址:\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*

27、提取信息中的图片链接:(s|S)(r|R)(c|C) *= *(‘|”)?(\w|\\|\/|\.)+(‘|”| *|>)?

28、提取信息中的IP地址:(\d+)\.(\d+)\.(\d+)\.(\d+)

29、提取信息中的中国手机号码:(86)*0*13\d{9}

30、提取信息中的中国固定电话号码:(\(\d{3,4}\)|\d{3,4}-|\s)?\d{8}

31、提取信息中的中国电话号码(包括移动和固定电话):(\(\d{3,4}\)|\d{3,4}-|\s)?\d{7,14}

32、提取信息中的中国邮政编码:[1-9]{1}(\d+){5}

33、提取信息中的浮点数(即小数):(-?\d*)\.?\d+

34、提取信息中的任何数字 :(-?\d*)(\.\d+)?

35、IP:(\d+)\.(\d+)\.(\d+)\.(\d+)

36、电话区号:/^0\d{2,3}$/

37、腾讯QQ号:^[1-9]*[1-9][0-9]*$

38、帐号(字母开头,允许5-16字节,允许字母数字下划线):^[a-zA-Z][a-zA-Z0-9_]{4,15}$

39、中文、英文、数字及下划线:^[\u4e00-\u9fa5_a-zA-Z0-9]+$