糯米文學吧

位置:首頁 > 計算機 > php語言

5個超級有用的php片段

php語言1.33W

儘管PHP經常被人詬病,被人貶低,被人當玩笑開,事實證明,PHP是全世界網站開發中使用率最高的'編程語言。PHP最大的缺點是太簡單,語法不嚴謹,框架體系很弱,但這也是它最大的優點,一個有點編程背景的普通人,只需要學習PHP半天時間,就可以上手開始開發web應用了

5個超級有用的php片段

  一、黑名單過濾

function is_spam($text, $file, $split = ':', $regex = fALse){

$handle = fopen($file, 'rb');

$contents = fread($handle, filesize($file));

fclose($handle);

$lines = explode("n", $contents);

$arr = array();

foreach($lines as $line){

list($word, $count) = explode($split, $line);

if($regex)

$arr[$word] = $count;

else

$arr[preg_quote($word)] = $count;

}

preg_match_all("~"ode('|', array_keys($arr))."~", $text, $matches);

$temp = array();

foreach($matches[0] as $match){

if(!in_array($match, $temp)){

$temp[$match] = $temp[$match] + 1;

if($temp[$match] >= $arr[$word])

return true;

}

}

return false;

}

$file = '';

$str = 'This string has cat, dog word';

if(is_spam($str, $file))

echo 'this is spam';

else

echo 'this is not spam';

ab:3

dog:3

cat:2

monkey:2

  二、隨機顏色生成器

複製代碼 代碼如下:

function randomColor() {

$str = '#';

for($i = 0 ; $i < 6 ; $i++) {

$randNum = rand(0 , 15);

switch ($randNum) {

case 10: $randNum = 'A'; break;

case 11: $randNum = 'B'; break;

case 12: $randNum = 'C'; break;

case 13: $randNum = 'D'; break;

case 14: $randNum = 'E'; break;

case 15: $randNum = 'F'; break;

}

$str .= $randNum;

}

return $str;

}

$color = randomColor();

  三、從網絡下載文件

複製代碼 代碼如下:

set_time_limit(0);

// Supports all file types

// URL Here:

$url = '_';

$pi = pathinfo($url);

$ext = $pi['extension'];

$name = $pi['filename'];

// create a new cURL resource

$ch = curl_init();

// set URL and other appropriate options

curl_setopt($ch, CURLOPT_URL, $url);

curl_setopt($ch, CURLOPT_HEADER, false);

curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);

curl_setopt($ch, CURLOPT_AUTOREFERER, true);

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// grab URL and pass it to the browser

$opt = curl_exec($ch);

// close cURL resource, and free up system resources

curl_close($ch);

$saveFile = $name.'.'.$ext;

if(preg_match("/[^0-9a-z._-]/i", $saveFile))

$saveFile = md5(microtime(true)).'.'.$ext;

$handle = fopen($saveFile, 'wb');

fwrite($handle, $opt);

fclose($handle);

  四、Alexa/Google Page Rank

function page_rank($page, $type = 'alexa'){

switch($type){

case 'alexa':

$url = '';

$handle = fopen($url.$page, 'r');

break;

case 'google':

$url = '#39;;

$handle = fopen($url.'http://'.$page, 'r');

break;

}

$content = stream_get_contents($handle);

fclose($handle);

$content = preg_replace("~(n|t|ss+)~",'', $content);

switch($type){

case 'alexa':

if(preg_match('~

(.+?)

~im',$content,$matches)){

return $matches[2];

}else{

return FALSE;

}

break;

case 'google':

$rank = explode(':',$content);

if($rank[2] != '')

return $rank[2];

else

return FALSE;

break;

標籤:PHP 片段