php开发中实用的PHP代码片段

1.关键词高亮

 代码如下 复制代码

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的用户

 代码如下 复制代码

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.自动生成密码

 代码如下 复制代码

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';
 } www,111cn.net
 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文件

 代码如下 复制代码

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("rn", "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.获取短网址

 代码如下 复制代码
function getTinyUrl($url) {
    return file_get_contents("http://tinyurl.com/api-create.php?url=".$url);
}

6.根据生日计算年龄

 代码如下 复制代码

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") – $year;
 $month_diff = date("m") – $month;
 $day_diff = date("d") – $day;
 if ($day_diff < 0 || $month_diff < 0) $year_diff–;

 return $year_diff;
}

7.计算执行时间

 代码如下 复制代码

//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的维护模式
function maintenance($mode = FALSE){
    if($mode){  www.111cn.net

        if(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" /&glt;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。

 

 代码如下 复制代码
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;
        }
 
    }

 判断一张图片的主色调

下面这个代码非常实用,能帮助你判断一张图片中的主色调,你可以分析任何图片。

 

 代码如下 复制代码
$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' . "rn";
 
    // 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;
时间: 2024-09-20 00:00:36

php开发中实用的PHP代码片段的相关文章

10个简单实用的 jQuery 代码片段

尽管各种 JavaScirpt 框架和库层出不穷,jQuery 仍然是 Web 前端开发中最常用的工具库. 今天,向大家分享我觉得在网站开发中10个简单实用的 jQuery 代码片段. 1.平滑滚动到锚点 // HTML: // <h1 id="anchor">Lorem Ipsum</h1> // <p><a href="#anchor" class="topLink">Back to Top&l

高效Web开发的10个jQuery代码片段_jquery

在过去的几年中,jQuery一直是使用最为广泛的JavaScript脚本库.今天我们将为各位Web开发者提供10个最实用的jQuery代码片段,有需要的开发者可以保存起来.  1.检测Internet Explorer版本  当涉及到CSS设计时,对开发者和设计者而言Internet Explorer一直是个问题.尽管IE6的黑暗时代已经过去,IE也越来越不流行,它始终是一个能够容易检测的好东西.当然了,下面的代码也能用于检测别的浏览器. $(document).ready(function()

一些实用的jQuery代码片段收集_jquery

下边这些jQuery片段只是很少的一部分,如果您在学习过程中也遇到过一些常用的jQuery代码,欢迎分享.下边就让我们看看这些有代码片段. 1.jQuery得到用户IP: 复制代码 代码如下: $.getJSON("http://jsonip.appspot.com?callback=?", function (data) { alert("Your ip: " + data.ip); }); 2.jQuery查看图片的宽度和高度: 复制代码 代码如下: var t

安卓 app 形状 绘制-请教,安卓app开发中,能用代码绘制一个纯文本意义的纯色的胶囊形状吗

问题描述 请教,安卓app开发中,能用代码绘制一个纯文本意义的纯色的胶囊形状吗 请教,安卓app开发中,能用代码绘制一个纯文本意义的纯色的胶囊形状吗,还是要用png图片代替呢,各有什么有缺点呢 解决方案 可以直接画,定义圆角的弧度,其他用纯色填充,形如: radius就是角度 字面意思比较清楚,你看看 <?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://s

PHP开发中常用的十个代码样例_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($w

java开发中通用分页类代码

java开发中通用分页类代码 在java中要分页我们必须要有数据库教程,所以我们先准备下数据库,其数据库脚步如下: --以下是创建数据库和数据库表以及向数据库插入数据   use master  Go  if exists(select * from sysdatabases where name='pagination')  drop database pagination  Go  create database pagination  Go  use pagination  Go  cre

分享12个实用的jQuery代码片段_jquery

jQuery是一款优秀的JavaScript库,它在WEB开发者和网页设计师中非常出名,帮助网页设计师开发出很多有创意和漂亮的WEB页面. 本文主要分享了12个有用的jQuery技巧,具体内容如下 下面是我收集的一些小技巧,这些技巧将帮助你提高你网站布局和应用的创意性以及功能性. 一.在新窗口打开链接 用这个代码,你点击超文本链接时会在新窗口中打开,为用户带来更好的体验: $(document).ready(function() { //select all anchor tags that h

php开发中实用的两条sql

这两天项目开发中,需要实现一些比较实用的功能,用了两个使用的sql,总结一下,怕下次忘记了. 1. 检索数据库中跟提交的内容相匹配的内容 比如:提交的数据是"游泳",那么数据库中有"我喜欢游泳"字样的就算是匹配,但是这样一来,还是不够,比如我提交的是"周末去游泳",数据库中有"游泳"的内容,其实意思类似,但是却使用like找不到的,于是想到下面的sql,已经封装成函数了:  function getRelationTags($

12 个非常实用的 jQuery 代码片段

jQuery是一个非常流行而且实用的JavaScript前端框架,本文并不是介绍jQuery的特效动画,而是分享一些平时积累的12个jQuery实用代码片段,希望对你有所帮助. 1. 导航菜单背景切换效果 在项目的前端页面里,相对于其它的导航菜单,激活的导航菜单需要设置不同的背景.这种效果实现的方式有很多种,下面是使用JQuery实现的一种方式: <ul id='nav'>      <li>导航一</li>      <li>导航二</li>