ThinkPHP 用多了,原生PHP都快不会了,不行,不行不行
跨域头 header('Access-Control-Allow-Origin:*');
PHP跳转页面
header("Location: https://note.coccoo.cc");
//确保重定向后,后续代码不会被执行
exit;
```
### PHP获取html中img标签的src值(正则表达式)
> 实现功能主要是在`富文本编辑器`提交过来的数据,包含了所有的html样式,但是我要根据富文本提交过来的数据判断有没有图片,如果有的话就把图片提取出来当`封面`,如果没有就给它一个`默认的封面`
//content 富文本内容
//matches 提取出来的包含src的数组
//pic 最终的src值
if (preg_match('/<img.+src=\"?(.+\.(jpg|gif|bmp|bnp|png))\"?.+>/i',$content,$matches)){
//得到图片地址结尾的位置
if ($num = strpos($matches[1],'"')){
//截取字符串,得到真正图片地址
$pic = substr($matches[1],0,$num);
}else{
$pic = $matches[1];
}
}
### mysqli连接数据库(可能)常用功能
> 现在貌似`mysql_`函数都慢慢被废弃了,开始转用`mysqli_`函数,比如`mysqli_connect`
设置编码
$con = mysqli_connect($host,$username,$password,$db) or die("Unable to connect to the MySQL!");
mysqli_query($con,"set names 'utf8'");//设置编码
开启事务
$con->autocommit(false);//开启事务
$res1 = mysqli_query($con,$sql1);//第一条操作
$res2 = mysqli_query($con,$sql2);//第二条操作
if ($res1 && $res2){
//提交事务
$con->commit();
//关闭连接
mysqli_close($con);
}else{
//回滚
$con->rollback();
}
### 判断某时间戳是否在今年
> 判断某个时间戳是不是在今年,如果是,就不显示带年份,如果不是,就显示年份时间
//$dis_time 要展示出来的时间
//date('Y',time()) == date('Y',$dis_time) 判断时间戳是否是今年
$dis_time = (date('Y',time()) == date('Y',$dis_time)) ? date('m-d H:i',$dis_time) : date('y-m-d H:i',$dis_time);
这样展示出来的数据就有两种形式,`06-29 12:28` 或者 `2008-07-22 12:28`
### 时间戳转换成微信朋友圈形式
> 把时间戳转换成类似朋友圈的形式,比如`一分钟前`,`两天前`之类的
//@param $addTime 传进去的时间戳
//return $timeStr 转换后的时间
public function getTime($addTime){
$nowTime = time();//当前时间
if($addTime > $nowTime) {
return "";
}
$dTime = $nowTime-$addTime;//时间差
$year = intval($dTime/2592000/12);//年数
$month = intval($dTime/2592000);//月数
$day = intval($dTime/86400);//天数
$hour = intval($dTime/3600);//小时
$min = intval($dTime/60);//分钟
if ($min<1){
$timeStr = '刚刚';
}else if ($hour < 1){
//分钟处理
$timeStr = $min.'分钟前';
}else if ($day<1){
//小时处理
$timeStr = $hour.'小时前';
}else if ($month<1){
//天数处理
$timeStr = $day.'天前';
}else if ($year<1){
//月数处理
$timeStr = $month.'月前';
}else{
//年数处理
$timeStr = $year.'年前';
}
return $timeStr;
}
评论 (0)