php开发中实用的PHP代码片段
下面我们一起来看我整理了在php开发中一些常用的php函数整理,希望这些函数代码地各位同学同样有帮助哦。
1.关键词高亮
<?php
function highlight($sString, $aWords) {
if (!is_array($aWords) || empty($aWords) || !is_string($sString)) {
return false;
}
$sWords = implode('|', $aWords);
return preg_replace('@b(' . $sWords . ')b@si', '<strong style="background-color:yellow">$1</strong>', $sString);
}
?>2.获取你的Feedburner的用户
<?php
function get_average_readers($feed_id, $interval = 7) {
$today = date('Y-m-d', strtotime("now"));
$ago = date('Y-m-d', strtotime("-" . $interval . " days"));
$feed_url = "https://feedburner.google.com/api/awareness/1.0/GetFeedData?uri=" . $feed_id . "&dates=" . $ago . "," . $today;
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $feed_url);
$data = curl_exec($ch);
curl_close($ch);
$xml = new SimpleXMLElement($data);
$fb = $xml->feed->entry['circulation'];
$nb = 0;
foreach ($xml->feed->children() as $circ) {
$nb+= $circ['circulation'];
}
return round($nb / $interval);
}
?>3.自动生成密码
<?php
function generatePassword($length = 9, $strength = 0) {
$vowels = 'aeuy';
$consonants = 'bdghjmnpqrstvz';
if ($strength >= 1) {
$consonants.= 'BDGHJLMNPQRSTVWXZ';
}
if ($strength >= 2) {
$vowels.= "AEUY";
}
if ($strength >= 4) {
$consonants.= '23456789';
}
if ($strength >= 8) {
$vowels.= '@#$%';
}
$password = '';
$alt = time() % 2;
for ($i = 0; $i < $length; $i++) {
if ($alt == 1) {
$password.= $consonants[(rand() % strlen($consonants)) ];
$alt = 0;
} else {
$password.= $vowels[(rand() % strlen($vowels)) ];
$alt = 1;
}
}
return $password;
}
?>4.压缩多个CSS文件
<?php
header('Content-type: text/css');
ob_start("compress");
function compress($buffer) {
/* remove comments */
$buffer = preg_replace('!/*[^*]**+([^/][^*]**+)*/!', '', $buffer);
/* remove tabs, spaces, newlines, etc. */
$buffer = str_replace(array(
"\r\n",
"\r",
"\n",
"\t",
' ',
' ',
' '
) , '', $buffer);
return $buffer;
}
/* your css files */
include ('master.css');
include ('typography.css');
include ('grid.css');
include ('print.css');
include ('handheld.css');
ob_end_flush();
?>5.获取短网址
<?php
function getTinyUrl($url) {
return file_get_contents("http://tinyurl.com/api-create.php?url=".$url);
}
?>6.根据生日计算年龄
<?php
function age($date) {
$year_diff = '';
$time = strtotime($date);
if (FALSE === $time) {
return '';
}
$date = date('Y-m-d', $time);
list($year, $month, $day) = explode("-", $date);
$year_diff = date("Y") & ndash;
$year;
$month_diff = date("m") & ndash;
$month;
$day_diff = date("d") & ndash;
$day;
if ($day_diff < 0 || $month_diff < 0) $year_diff & ndash;;
return $year_diff;
}
?>7.计算执行时间
<?php //Create a variable for start time $time_start = microtime(true); // Place your PHP/HTML/JavaScript/CSS/Etc. Here //Create a variable for end time $time_end = microtime(true); //Subtract the two times to get seconds $time = $time_end - $time_start; echo 'Script took ' . $time . ' seconds to execute'; ?>
8.PHP的维护模式
<?php
function maintenance($mode = FALSE) {
if ($mode) {
www . phprm . comif (basename($_SERVER['SCRIPT_FILENAME']) != 'maintenance.php') {
header("Location: http://example.com/maintenance.php");
exit;
}
} else {
if (basename($_SERVER['SCRIPT_FILENAME']) == 'maintenance.php') {
header("Location: http://example.com/");
exit;
}
}
}
?>9.阻止CSS样式被缓存
<link href="/stylesheet.css?<?php echo time(); ?>" rel="stylesheet" type="text/css" >
10.数字增加 stndrd 等
function make_ranked($rank) {
$last = substr( $rank, -1 );
$seclast = substr( $rank, -2, -1 );
if( $last > 3 || $last == 0 ) $ext = 'th';
else if( $last == 3 ) $ext = 'rd';
else if( $last == 2 ) $ext = 'nd';
else $ext = 'st';
if( $last == 1 && $seclast == 1) $ext = 'th';
if( $last == 2 && $seclast == 1) $ext = 'th';
if( $last == 3 && $seclast == 1) $ext = 'th';
return $rank.$ext;
}通过IP判断来源
这是一个非常实用的代码片段,可以帮助你通过IP来判断访客来源。下面的方法通过接收一个参数,然后返回IP所在地点。如果没有找到,则返回UNKNOWN。
<?php
function detect_city($ip) {
$default = 'UNKNOWN';
if (!is_string($ip) || strlen($ip) < 1 || $ip == '127.0.0.1' || $ip == 'localhost') $ip = '8.8.8.8';
$curlopt_useragent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2) Gecko/20100115 Firefox/3.6 (.NET CLR 3.5.30729)';
$url = 'http://ipinfodb.com/ip_locator.php?ip=' . urlencode($ip);
$ch = curl_init();
$curl_opt = array(
CURLOPT_FOLLOWLOCATION => 1,
CURLOPT_HEADER => 0,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_USERAGENT => $curlopt_useragent,
CURLOPT_URL => $url,
CURLOPT_TIMEOUT => 1,
CURLOPT_REFERER => 'http://' . $_SERVER['HTTP_HOST'],
);
curl_setopt_array($ch, $curl_opt);
$content = curl_exec($ch);
if (!is_null($curl_info)) {
$curl_info = curl_getinfo($ch);
}
curl_close($ch);
if (preg_match('{<li>City : ([^<]*)</li>}i', $content, $regs)) {
$city = $regs[1];
}
if (preg_match('{<li>State/Province : ([^<]*)</li>}i', $content, $regs)) {
$state = $regs[1];
}
if ($city != '' && $state != '') {
$location = $city . ', ' . $state;
return $location;
} else {
return $default;
}
}
?>判断一张图片的主色调
下面这个代码非常实用,能帮助你判断一张图片中的主色调,你可以分析任何图片。
<?php
$i = imagecreatefromjpeg("image.jpg");
for ($x = 0; $x < imagesx($i); $x++) {
for ($y = 0; $y < imagesy($i); $y++) {
$rgb = imagecolorat($i, $x, $y);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> &0xFF;
$b = $rgb & 0xFF;
$rTotal+= $r;
$gTotal+= $g;
$bTotal+= $b;
$total++;
}
}
$rAverage = round($rTotal / $total);
$gAverage = round($gTotal / $total);
$bAverage = round($bTotal / $total);
?>不显示PHP错误而发送电子邮件取代之
如果你不想在页面中显示PHP错误,也可以通过email来获取错误信息。下面的代码可以帮助你实现。
<?php
// Our custom error handler
function nettuts_error_handler($number, $message, $file, $line, $vars) {
$email = "
<p>An error ($number) occurred on line
<strong>$line</strong> and in the <strong>file: $file.</strong>
<p> $message </p>";
$email.= "<pre>" . print_r($vars, 1) . "</pre>";
$headers = 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
// Email the error to someone...
error_log($email, 1, 'you@youremail.com', $headers);
// Make sure that you decide how to respond to errors (on the user's side)
// Either echo an error message, or kill the entire project. Up to you...
// The code below ensures that we only "die" if the error was more than
// just a NOTICE.
if (($number !== E_NOTICE) && ($number < 2048)) {
die("There was an error. Please try again later.");
}
}
// We should use our custom function to handle errors.
set_error_handler('nettuts_error_handler');
// Trigger an error... (var doesn't exist)
echo $somevarthatdoesnotexist;
?>教程网址:http://www.phprm.com/code/58810.html
欢迎收藏∩_∩但请保留本文链接。