开发时常用例子

php 判断日期

$date = '2020-08-04 12:43:38';
if(date('Y-m-d H:i:s',strtotime($date)) == $date)
{
	echo 'yes';
}
else {
	echo 'no';
}

PHP列表的排号

//$amount:记录总数
//$page:当前页数
//$pageSize:总页数

$i = 1;
while($row=mysql_fetch_array($result)){

	$number = $amount - (($page * $pageSize) - $pageSize) + 1 - $i;

	...

	$i++;
}

字符串去掉重复的字符

// 字符串去掉重复的字符
function delete_repeate_char($str) {
	$str = preg_split('/(?<!^)(?!$)/u', $str ); 
	$charlist = array_unique($str); 
	return implode('', $charlist);
}

去掉所有字母

// 去掉所有字母
function filter_letters($str) {

	$str = preg_replace("/[a-z]/","",$str);//去掉所有小写字母
	$str = preg_replace("/[A-Z]/","",$str);//去掉所有大写字母
	return $str;
}

检查缺少的数字

//检查0到9中的数字范围下,$data里缺少哪个数字
$full = range(0, 9);
$diff = array_diff($full, $data);

字符串和数组转换

$data = str_split($str);// 把字符串转化为数组
$str2 = implode('',$diff);// 数组转字符串

字符串中过滤空格符号,HTML CSS SCRIPT

$contents_temp = trim($contents);
			
//  string 过滤空白
$search = array(" "," ","\n","\r","\t");
$replace = array("","","","","");
$contents_temp = str_replace($search, $replace, $contents_temp);

$contents_temp = preg_replace("/(\s|\&nbsp\;| |\xc2\xa0)/", " ", strip_tags($contents_temp));

// string 过滤html css script
$contents_temp = preg_replace( "@<script(.*?)</script>@is", "", $contents_temp );
$contents_temp = preg_replace( "@<iframe(.*?)</iframe>@is", "", $contents_temp );
$contents_temp = preg_replace( "@<style(.*?)</style>@is", "", $contents_temp );
$contents_temp = preg_replace( "@<(.*?)>@is", "", $contents_temp );
$contents_temp= htmlspecialchars_decode($contents_temp);
$contents_temp= preg_replace("/<(.*?)>/","",$contents_temp);
			

取百分比

// $num 数量,$vote_num 总数,$item_percent 占总数的百分比
$item_percent = round(($num / $vote_num) * 100);

数字前补0

// 1~9时加0,第二个参数可能是总共要几个位数,09就是两位,第三个参数是要加什么
str_pad($startMonth,2,"0",STR_PAD_LEFT);

php获取当前访问的完整url地址

function GetCurUrl(){
	$url='http://';
	if(isset($_SERVER['HTTPS'])&&$_SERVER['HTTPS']=='on'){
		$url='https://';
	}
	if($_SERVER['SERVER_PORT']!='80'){
		$url.=$_SERVER['SERVER_NAME'].':'.$_SERVER['SERVER_PORT'].$_SERVER['REQUEST_URI'];
	}else{
		$url.=$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
	}
	return $url;
}

检查URL是否合法

<?php 
$url='http://www.asd.com';// 合法的形式
if(!preg_match('/http:\/\/[\w.]+[\w\/]*[\w.]*\??[\w=&\+\%]*/is',$url)){
    echo 'url地址非法';
}else{
    echo 'url地址合法';
}
?> 

date函数相关

date('Y-m-d H:i:s');// 常用的
//月:m带0,n不带0
//日:d带0,j不带0
date('Y-m-d'); // 2020-01-14
date('Y-n-j');  // 2020-1-14

mktime()函数相关

时间戳转换工具网址

// 某年某月有多少天
echo date("t",mktime(0,0,0,$month,1,$year));

// 某年某月的第一天是星期几
// 0星期日,1~5周一到周五,6星期六
echo date("w",mktime(0,0,0,$month,1,$year));

// 某年某月最后一天是星期几
$days = date("t",mktime(0,0,0,$month,1,$year));
echo date("w",mktime(0,0,0,$month,$days,$year));

// 以今天【2020-01-14】为基准
// 获取今日开始时间戳和结束时间戳
// 2020-01-14 08:00:00 
$start = mktime(0,0,0,date('m'),date('d'),date('Y'));
// 2020-01-15 07:59:59
$end = mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1;

//获取本月起始时间戳和结束时间戳
$beginThismonth=mktime(0,0,0,date('m'),1,date('Y'));
$endThismonth=mktime(23,59,59,date('m'),date('t'),date('Y'));

//获取昨日起始时间戳和结束时间戳
$beginYesterday = mktime(0,0,0,date('m'),date('d')-1,date('Y'));
$endYesterday = mktime(0,0,0,date('m'),date('d'),date('Y'))-1;

//获取上周起始时间戳和结束时间戳
$beginLastweek = mktime(0,0,0,date('m'),date('d')-date('w')+1-7,date('Y'));
$endLastweek = mktime(23,59,59,date('m'),date('d')-date('w')+7-7,date('Y'));

格式化数字

echo number_format("5000000")."<br>";
5,000,000
echo number_format("5000000",2)."<br>";
5,000,000.00
echo number_format("5000000",2,",",".");
5.000.000,00

小数点后留两个位置,并四舍五入,空位以0补填

$w = sprintf('%.2f',round(123123.1231,2));

通过类名查找这个类所在的路径(即实际引用的是哪个类)

$func = new ReflectionClass(trim('a'));
echo $func->getFileName();

通过函数名找函数所在的文件

Reflection::export(new ReflectionFunction("html_end"));
die;

字符串中a标签相关的标签干掉,只留内容

$str = htmlspecialchars_decode($str);
$str = preg_replace("/<a[^>]*>(.*?)<\/a>/is", "$1", $str);

取得完整当前url

$http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on')|| (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) &&$_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' :'http://';
$url = $http_type.$_SERVER['HTTP_HOST'];

如果不是https,就以https重定向

if(!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] == 'off'){
    Header("HTTP/1.1 301 Moved Permanently");
    header('Location: https://'.$_SERVER['HTTP_HOST'].$port.$_SERVER['REQUEST_URI']);
}

判断字符串$url带不带http://,不带的话就加上去

$preg = "/^http(s)?:\\/\\/.+/";
if(!preg_match($preg,$url)){
	$url = "http://".$url;
}

urlencode进行转换后 为什么空格是+号 不是%20

// 返回字符串,此字符串中除了-_. 之外的所有非字母数字字符都将被替换成百分号(%)后跟两位十六进制数,空格则编码为加号(+)。
string urlencode(string $str)

//解决方法:返回字符串,此字符串中除了-_. 之外的所有非字母数字字符都将被替换成百分号(%)后跟两位十六进制数。
string rawurlencode(string $str)

url中飘来encoding的韩文时,如下decoding

$str = iconv('euc-kr', 'utf-8', urldecode($_GET['r_name']))

取得UUID

function getUuid() {     
	static $guid = '';
	$uid = uniqid("", true);
	$data = $namespace;
	$data .= $_SERVER['REQUEST_TIME'];
	$data .= $_SERVER['HTTP_USER_AGENT'];
	$data .= $_SERVER['LOCAL_ADDR'];
	$data .= $_SERVER['LOCAL_PORT'];
	$data .= $_SERVER['REMOTE_ADDR'];
	$data .= $_SERVER['REMOTE_PORT'];
	$hash = strtoupper(hash('ripemd128', $uid . $guid . md5($data)));
	$guid = '' .   
			substr($hash,  0,  8) . 
			'-' .
			substr($hash,  8,  4) .
			'-' .
			substr($hash, 12,  4) .
			'-' .
			substr($hash, 16,  4) .
			'-' .
			substr($hash, 20, 12) .
			'';
	return $guid;
 }
 // 第二个
function getUUID($len){
	$chars='ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
	$string=time();
	for(;$len>=1;$len--)
	{
		$position=rand()%strlen($chars);
		$position2=rand()%strlen($string);
		$string=substr_replace($string,substr($chars,$position,1),$position2,0);
	}
	return $string;
}

// 第三个
function makeCDKey(){
	$code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
	$rand = $code[rand(0,25)]
		.strtoupper(dechex(date('m')))
		.date('d').substr(time(),-5)
		.substr(microtime(),2,5)
		.sprintf('%02d',rand(0,99));
	for(
		$a = md5( $rand, true ),
		$s = '0123456789ABCDEFGHIJKLMNOPQRSTUV',
		$d = '',
		$f = 0;
		$f < 8;
		$g = ord( $a[ $f ] ),
		$d .= $s[ ( $g ^ ord( $a[ $f + 8 ] ) ) - $g & 0x1F ],
		$f++
	);
	return  $d;
}

客户端是不是mobile

function isMobile()
{ 
	if (isset ($_SERVER['HTTP_X_WAP_PROFILE']))
	{
		return true;
	} 
	if (isset ($_SERVER['HTTP_VIA']))
	{ 
		return stristr($_SERVER['HTTP_VIA'], "wap") ? true : false;
	} 
	if (isset ($_SERVER['HTTP_USER_AGENT']))
	{
		$clientkeywords = array ('nokia',
			'sony',
			'ericsson',
			'mot',
			'samsung',
			'htc',
			'sgh',
			'lg',
			'sharp',
			'sie-',
			'philips',
			'panasonic',
			'alcatel',
			'lenovo',
			'iphone',
			'ipod',
			'blackberry',
			'meizu',
			'android',
			'netfront',
			'symbian',
			'ucweb',
			'windowsce',
			'palm',
			'operamini',
			'operamobi',
			'openwave',
			'nexusone',
			'cldc',
			'midp',
			'wap',
			'mobile'
			); 
		if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT'])))
		{
			return true;
		} 
	} 
	if (isset ($_SERVER['HTTP_ACCEPT']))
	{ 
		if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html'))))
		{
			return true;
		} 
	} 
	return false;
} 

数据库查询时

// 用两次同样的结果集资源时,while($row_join1 = mysql_fetch_array($res_join)) {

mysql_data_seek( $res_join, 0 );// 两个循环之间加这玩意,不然第二次循环时值都取不出来

时间比较

// $last_vote 的一个小时后,一天后,一周后
//$now = strtotime(date("Y-m-d H:i:s",time()));

$yigexiaoshihou = strtotime(date("Y-m-d H:i:s",strtotime("+1 hour",strtotime($last_vote))));
//$yigexiaoshihou = date("Y-m-d H:i:s",strtotime("+1 hour",strtotime($last_vote)));

$yitianhou = strtotime(date("Y-m-d H:i:s",strtotime("+1 day",strtotime($last_vote))));
//$yitianhou = date("Y-m-d H:i:s",strtotime("+1 day",strtotime($last_vote)));

$yizhouhou = strtotime(date("Y-m-d H:i:s",strtotime("+1 week",strtotime($last_vote))));
//$yizhouhou = date("Y-m-d H:i:s",strtotime("+1 week",strtotime($last_vote)));

xss sql注入

// 预防XSS攻击
<?php  
if (isset($_POST['name'])){  
    $str = trim($_POST['name']);  //清理空格  
    $str = strip_tags($str);   //过滤html标签  
    $str = htmlspecialchars($str);   //将字符内容转化为html实体  
    // html_entity_decode 与 上面的反过来
    $str = addslashes($str);  //防止SQL注入
    echo $str;  
} 

$no = str_replace ( array ('"', "\\", "'", "/", "..", "../", "./", "//","<",">","'","script","alert","&gt" ,";","&lt","(",")"), '', $no );

// SQL注入防止
if (!get_magic_quotes_gpc())
{
	$alias = addslashes($alias);
}

$alias= htmlspecialchars($alias);

php获取操作系统

$os='';
$agent=$_SERVER['HTTP_USER_AGENT'];

if (preg_match('/win/i', $agent) && strpos($agent, '95'))
{
  $os = 'Windows 95';
}
else if (preg_match('/win 9x/i', $agent) && strpos($agent, '4.90'))
{
  $os = 'Windows ME';
}
else if (preg_match('/win/i', $agent) && preg_match('/98/i', $agent))
{
  $os = 'Windows 98';
}
else if (preg_match('/win/i', $agent) && preg_match('/nt 6.0/i', $agent))
{
  $os = 'Windows Vista';
}
else if (preg_match('/win/i', $agent) && preg_match('/nt 6.1/i', $agent))
{
  $os = 'Windows 7';
}
  else if (preg_match('/win/i', $agent) && preg_match('/nt 6.2/i', $agent))
{
  $os = 'Windows 8';
}else if(preg_match('/win/i', $agent) && preg_match('/nt 10.0/i', $agent))
{
  $os = 'Windows 10';#添加win10判断
}else if (preg_match('/win/i', $agent) && preg_match('/nt 5.1/i', $agent))
{
  $os = 'Windows XP';
}
else if (preg_match('/win/i', $agent) && preg_match('/nt 5/i', $agent))
{
  $os = 'Windows 2000';
}
else if (preg_match('/win/i', $agent) && preg_match('/nt/i', $agent))
{
  $os = 'Windows NT';
}
else if (preg_match('/win/i', $agent) && preg_match('/32/i', $agent))
{
  $os = 'Windows 32';
}
else if (preg_match('/linux/i', $agent))
{
  $os = 'Linux';
}
else if (preg_match('/unix/i', $agent))
{
  $os = 'Unix';
}
else if (preg_match('/sun/i', $agent) && preg_match('/os/i', $agent))
{
  $os = 'SunOS';
}
else if (preg_match('/ibm/i', $agent) && preg_match('/os/i', $agent))
{
  $os = 'IBM OS/2';
}
else if (preg_match('/Mac/i', $agent) && preg_match('/PC/i', $agent))
{
  $os = 'Macintosh';
}
else if (preg_match('/PowerPC/i', $agent))
{
  $os = 'PowerPC';
}
else if (preg_match('/AIX/i', $agent))
{
  $os = 'AIX';
}
else if (preg_match('/HPUX/i', $agent))
{
  $os = 'HPUX';
}
else if (preg_match('/NetBSD/i', $agent))
{
  $os = 'NetBSD';
}
else if (preg_match('/BSD/i', $agent))
{
  $os = 'BSD';
}
else if (preg_match('/OSF1/i', $agent))
{
  $os = 'OSF1';
}
else if (preg_match('/IRIX/i', $agent))
{
  $os = 'IRIX';
}
else if (preg_match('/FreeBSD/i', $agent))
{
  $os = 'FreeBSD';
}
else if (preg_match('/teleport/i', $agent))
{
  $os = 'teleport';
}
else if (preg_match('/flashget/i', $agent))
{
  $os = 'flashget';
}
else if (preg_match('/webzip/i', $agent))
{
  $os = 'webzip';
}
else if (preg_match('/offline/i', $agent))
{
  $os = 'offline';
}
else
{
  $os = '未知操作系统';
}

获取浏览器

// 获取浏览器
$sys = $_SERVER['HTTP_USER_AGENT'];  
if (stripos($sys, "Firefox/") > 0) {
   preg_match("/Firefox\/([^;)]+)+/i", $sys, $b);
   $exp[0] = "Firefox";
   $exp[1] = $b[1];  //获取火狐浏览器的版本号
} elseif (stripos($sys, "Maxthon") > 0) {
   preg_match("/Maxthon\/([\d\.]+)/", $sys, $aoyou);
   $exp[0] = "傲游";
   $exp[1] = $aoyou[1];
} elseif (stripos($sys, "MSIE") > 0) {
   preg_match("/MSIE\s+([^;)]+)+/i", $sys, $ie);
   $exp[0] = "IE";
   $exp[1] = $ie[1];  //获取IE的版本号
} elseif (stripos($sys, "OPR") > 0) {
       preg_match("/OPR\/([\d\.]+)/", $sys, $opera);
   $exp[0] = "Opera";
   $exp[1] = $opera[1];  
} elseif(stripos($sys, "Edge") > 0) {
   //win10 Edge浏览器 添加了chrome内核标记 在判断Chrome之前匹配
   preg_match("/Edge\/([\d\.]+)/", $sys, $Edge);
   $exp[0] = "Edge";
   $exp[1] = $Edge[1];
} elseif (stripos($sys, "Chrome") > 0) {
       preg_match("/Chrome\/([\d\.]+)/", $sys, $google);
   $exp[0] = "Chrome";
   $exp[1] = $google[1];  //获取google chrome的版本号
} elseif(stripos($sys,'rv:')>0 && stripos($sys,'Gecko')>0){
   preg_match("/rv:([\d\.]+)/", $sys, $IE);
       $exp[0] = "IE";
   $exp[1] = $IE[1];
}else {
  $exp[0] = "未知浏览器";
  $exp[1] = ""; 
}
$browser =  $exp[0].'('.$exp[1].')';

URL中的encoding韩文在PHPdecoding

$str = iconv('euc-kr', 'utf-8', urldecode($_GET['r_name']))

截取韩文字符串

// 截取韩文
if (strlen($asd)>67) $asd=mb_substr($asd,0,67,'utf-8') . '...';
// 数字或文字截取
if (strlen($str)>5) $str=substr($str,0,5) . '...';

//例子:
$title = "韩文";// 一个韩文等于3个长度
if (strlen($title)>18) {// 大于6个韩文字
	$title=mb_substr($title,0,6,'utf-8') . '...';// 截取前6个
}
echo $title;

列表数字从1开始

// 总记录数 - 一页条数 * (当前页码 - 1)
$article_num=$count - $pageSize*($pageNow-1); //列表数
for($i=0; $i<count($list); $i++){
	...
	$article_num--;
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值