PHP 函数
2021/6/15 12:21:26
本文主要是介绍PHP 函数,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
本文记录些有用的函数
过滤掉emoji表情
-
function filterEmoji($str)
-
{
-
$str = preg_replace_callback(
-
'/./u',
-
function (array $match) {
-
return strlen($match[0]) >= 4 ? '' : $match[0];
-
},
-
$str);
-
-
return $str;
-
}
获取 ip
-
function get_ip_address(){
-
foreach (array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR') as $key){
-
if (array_key_exists($key, $_SERVER) === true){
-
foreach (explode(',', $_SERVER[$key]) as $ip){
-
$ip = trim($ip); // just to be safe
-
if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false){
-
return $ip;
-
}
-
}
-
}
-
}
-
}
导出 excel
-
function exportData($fileName,$content){
-
header("Content-type: text/html; charset=utf-8");
-
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
-
header("Content-Type: application/vnd.ms-execl");
-
header("Content-Type: application/force-download");
-
header("Content-Type: application/download");
-
header("Content-Disposition: attachment; filename=".$fileName);
-
header("Content-Transfer-Encoding: binary");
-
header("Pragma: no-cache");
-
header("Expires: 0");
-
echo $content;exit;
-
}
安全 base64
-
//Base64编码原理与应用http://blog.xiayf.cn/2016/01/24/base64-encoding/
-
function urlsafe_base64_encode($data)
-
{
-
return strtr(base64_encode($data), ['+' => '-', '/' => '_', '=' => '']);
-
}
-
function urlsafe_base64_decode($data, $strict = false)
-
{
-
return base64_decode(strtr($data, '-_', '+/'), $strict);
-
}
-
function safeStrlen($str)
-
{
-
if (function_exists('mb_strlen')) {
-
return mb_strlen($str, '8bit');
-
}
-
return strlen($str);
-
}
httpbuildquery bug
-
//重温PHP手册http://www.powerxing.com/php-review-oop/
-
$arr=[
-
"x" => false,
-
"y" => "",
-
"z" => null
-
];
-
http_build_query($arr)
-
=> "x=0&y="
-
foreach($arr as $k=>$v){$r.=$k.'='.$v.'&';}
解析命令行
-
unction exp_command($str)
-
{
-
// 正则表达式
-
$regEx = '#(?:(?<s>[\'"])?(?<v>.+?)?(?:(?<!\\\\)\k<s>)|(?<u>[^\'"\s]+))#';
-
// 匹配所有
-
if(!preg_match_all($regEx, $str, $exp_list)) return false;
-
// 遍历所有结果
-
$cmd = array();
-
foreach ($exp_list['s'] as $id => $s) {
-
// 判断匹配到的值
-
$cmd[] = empty($s) ? $exp_list['u'][$id] : $exp_list['v'][$id];
-
}
-
return $cmd;
-
}
-
// 命令行字符串
-
$str = 'cmd -n "rel\'o\"a d" \'te"s\' t\' upload ""';
-
$cmd = exp_command($str);
-
print_r($cmd);
-
/* 打印输出结果
-
Array
-
(
-
[0] => cmd
-
[1] => -n
-
[2] => rel'o\"a d
-
[3] => te"s
-
[4] => t
-
[5] => upload
-
[6] =>
-
)
-
*/
求两个经纬度之间的距离
-
function getDistance($aLng, $aLat, $bLng, $bLat)
-
{
-
//将角度转为狐度https://www.lvtao.net/dev/1899.html
-
$aLng = deg2rad($aLng);
-
$aLat = deg2rad($aLat);
-
$bLng = deg2rad($bLng);
-
$bLat = deg2rad($bLat);
-
$lngDiff = $aLng - $bLng;
-
$latDiff = $aLat - $bLat;
-
$diff = 2 * asin(sqrt(pow(sin($latDiff / 2), 2) + cos($aLat) * cos($bLat) * pow(sin($lngDiff / 2), 2))) * 6378.137 * 1000;
-
return $diff;
-
}
-
-
echo getDistance(36.059907, 120.300687, 36.019983, 120.296447);
多条数据,根据权限随机展示
-
function getConsultant()
-
{
-
$data = array(
-
array('name'=>'user1','weights'=>1),
-
array('name'=>'user2','weights'=>2),
-
array('name'=>'user3','weights'=>3),
-
array('name'=>'user4','weights'=>4)
-
);
-
$weight = 0;
-
$users = array();
-
foreach ($data as $one) {
-
$oneWeight = (int)$one['weights'] ? $one['weights'] : 1;
-
$weight += $oneWeight;
-
for ($i = 0; $i < $oneWeight; $i ++) {
-
$users[] = $one;
-
}
-
}
-
return $users[rand(0, $weight-1)];
-
}
PHP多进程同时写文件
-
function ffwrite($filename,$content) {
-
$file = fopen("$filename","a");
-
while(1) {
-
if (flock($file,LOCK_EX))
-
{
-
fwrite($file,$content);
-
flock($file,LOCK_UN);
-
fclose($file);
-
break;
-
} else {
-
usleep(1000);
-
}
-
}
-
}
随机汉字
-
function genstr($num)
-
{
-
for($i=0;$i<=$num;$i++)
-
{
-
$str .= '&#'.rand(19968, 40869).';';
-
}
-
-
return mb_convert_encoding($str, "UTF-8", "HTML-ENTITIES");
-
}
-
echo genstr(mt_rand(1,8));
-
function genstr2($num)
-
{
-
for($i=0;$i<=$num;$i++)
-
{
-
$str .= chr(rand(0xB0,0xF7)).chr(rand(0xA1,0xFE));
-
}
-
-
return $str;
-
}
-
echo genstr2(mt_rand(1,8));
转换字节
-
function convert($size)
-
{
-
$unit=array('b','kb','mb','gb','tb','pb');
-
return @round($size/pow(1024,($i=floor(log($size,1024)))),2).$unit[$i];
-
}
-
echo convert(memory_get_usage(true));
一致性hash
-
function get_hash($str, $num=10){
-
$crc = crc32($str);
-
$nu = $crc % $num;
-
return $nu;
-
}
-
-
function genstr($num) {
-
return substr(str_shuffle('abcdefghijklmnupqrstuvwxyz'), 0, $num);
-
}
-
-
for ($i=1; $i<10000000; $i++) {
-
$str = genstr(5);
-
$crc = crc32($str);
-
$nu = get_hash($str);;
-
if (isset($count[$nu])) {
-
$count[$nu]++;
-
} else {
-
$count[$nu]=1;
-
}
-
}
-
print_r($count);
Base62
-
class Base62 {
-
-
private $string = "vPh7zZwA2LyU4bGq5tcVfIMxJi6XaSoK9CNp0OWljYTHQ8REnmu31BrdgeDkFs";
-
-
public function base62_encode($str) {
-
$out = '';
-
for($t=floor(log10($str)/log10(62)); $t>=0; $t--) {
-
$a = floor($str / pow(62, $t));
-
$out = $out.substr($this->string, $a, 1);
-
$str = $str - ($a * pow(62, $t));
-
}
-
return $out;
-
}
-
-
public function base62_decode($str) {
-
$out = 0;
-
$len = strlen($str) - 1;
-
for($t=0; $t<=$len; $t++) {
-
$out = $out + strpos($this->string, substr($str, $t, 1)) * pow(62, $len - $t);
-
}
-
return substr(sprintf("%f", $out), 0, -7);
-
}
-
}
-
$str = 1234567;
-
$object = new Base62();
-
echo $object->base62_encode($str) . "\n";
-
echo $object->base62_decode($object->base62_encode($str)) . "\n";
字符截取
-
function substr_utf8($str,$start,$length){
-
return implode("",array_slice(preg_split("//u",$str,-1,PREG_SPLIT_NO_EMPTY),$start,$length));
-
}
-
echo substr_count($str,'你');
用DOMXpath加载DOM
-
//创建一个DomDocument对象,用于处理一个HTML
-
$dom = new DOMDocument();
-
//从一个字符串加载HTML
-
@$dom->loadHTML($html);
-
//使该HTML规范化
-
$dom->normalize();
-
-
//用DOMXpath加载DOM,用于查询
-
$xpath = new DOMXPath($dom);
-
#获取所有的a标签的地址
-
$hrefs = $xpath->evaluate("/html/body//a//@href");
-
-
for ($i = 0; $i < $hrefs->length; $i++) {
-
$href = $hrefs->item($i);
-
$linktext = $href->nodeValue;
-
echo $linktext;
-
echo "<BR>";
-
-
}
计算两个以YYYY-MM-DD为格式的日期,相差几天
-
function getChaBetweenTwoDate($date1,$date2){
-
-
$Date_List_a1=explode("-",$date1);
-
$Date_List_a2=explode("-",$date2);
-
-
$d1=mktime(0,0,0,$Date_List_a1[1],$Date_List_a1[2],$Date_List_a1[0]);
-
-
$d2=mktime(0,0,0,$Date_List_a2[1],$Date_List_a2[2],$Date_List_a2[0]);
-
-
$Days=round(($d1-$d2)/3600/24);
-
-
return $Days;
-
}
-
-
echo getChaBetweenTwoDate('2010-08-11','2010-08-16');
static
-
class ParentClass {
-
public static function name()
-
{
-
return __CLASS__;
-
}
-
public static function create()
-
{
-
return new static();
-
}
-
public static function test()
-
{
-
return self::name(); //改为static::name() 就可以了
-
}
-
}
-
class ChildClass extends ParentClass {
-
public static function name()
-
{
-
return __CLASS__;
-
}
-
}
-
echo ChildClass::test();
并发请求
-
$requestUrls = [];
-
for ($i=0; $i<10; $i++) {
-
array_push($requestUrls, 'http://baidu.com');
-
}
-
$mh = curl_multi_init();
-
$chs = [];
-
foreach ($requestUrls as $url) {
-
$chs[] = $ch = curl_init();
-
curl_setopt($ch, CURLOPT_URL, $url);
-
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
-
curl_setopt($ch, CURLOPT_TIMEOUT, 3000);
-
curl_setopt($ch, CURLOPT_NOSIGNAL, true);
-
curl_setopt($ch, CURLOPT_HEADER, 0);
-
curl_setopt($ch, CURLOPT_PROXY, '127.0.0.1:8888');
-
curl_multi_add_handle($mh, $ch);
-
}
-
do {
-
curl_multi_exec($mh, $running);
-
curl_multi_select($mh);
-
} while ($running > 0);
-
$res = [];
-
foreach ($chs as $k => $ch) {
-
$res[] = curl_multi_getcontent($ch);
-
curl_multi_remove_handle($mh, $ch);
-
echo $k . ' success' . PHP_EOL;
-
}
-
curl_multi_close($mh);
几天后日期
-
function rangeDaysAfterTimeStamp($startTimestamp, $daysNum = 1)
-
{
-
$range = [];
-
-
do {
-
$range[] = date('Y-m-d 00:00:00', $startTimestamp + (-- $daysNum) * 86400);
-
} while ($daysNum);
-
-
rsort($range);
-
-
return $range;
-
}
-
>>> rangeDaysAfterTimeStamp(strtotime('2017-11-11'),7)
-
=> [
-
"2017-11-17 00:00:00",
-
"2017-11-16 00:00:00",
-
"2017-11-15 00:00:00",
-
"2017-11-14 00:00:00",
-
"2017-11-13 00:00:00",
-
"2017-11-12 00:00:00",
-
"2017-11-11 00:00:00"
-
]
-
function rangeDays($beginTimestamp, $endTimestamp)
-
{
-
$beginTimestamp = strtotime(date('Y-m-d', $beginTimestamp));
-
$endTimestamp = strtotime(date('Y-m-d', $endTimestamp));
-
-
$range = [];
-
$i = 0;
-
-
do {
-
$time = $beginTimestamp + $i * 86400;
-
$range[] = date('Y-m-d 00:00:00', $time);
-
$i++;
-
} while ($time < $endTimestamp);
-
-
return $range;
-
}
下载文件
-
$ch = curl_init();
-
-
$fp=fopen('./girl.jpg', 'w');
-
-
curl_setopt($ch, CURLOPT_URL, "http://远程服务器地址马赛克/girl.jpg");
-
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
-
curl_setopt($ch, CURLOPT_FILE, $fp);
-
-
$output = curl_exec($ch);
-
$info = curl_getinfo($ch);
-
-
fclose($fp);
-
-
$size = filesize("./girl.jpg");
-
if ($size != $info['size_download']) {
-
echo "下载的数据不完整,请重新下载";
-
} else {
-
echo "下载数据完整";
-
}
redis 消息推送
-
// ini_set(‘default_socket_timeout’, -1); https://github.com/TIGERB/easy-tips/blob/master/redis/subscribe-publish/subscribe.php
-
$redis = new \Redis();
-
$redis->pconnect('127.0.0.1', 6379);
-
//订阅
-
echo "订阅msg这个频道,等待消息推送... \n";
-
$redis->subscribe(['msg'], 'callfun');
-
function callfun($redis, $channel, $msg)
-
{
-
print_r([
-
'redis' => $redis,
-
'channel' => $channel,
-
'msg' => $msg
-
]);
-
}
-
$redis->publish('msg', '来自msg频道的推送');
-
echo "msg频道消息推送成功~ \n";
-
$redis->close();
xml
-
$format = <<<XML
-
<xml>
-
<Encrypt><![CDATA[%s]]></Encrypt>
-
<MsgSignature><![CDATA[%s]]></MsgSignature>
-
<TimeStamp>%s</TimeStamp>
-
<Nonce><![CDATA[%s]]></Nonce>
-
</xml>
-
XML;
-
$xml = new \DOMDocument();
-
$xml->loadXML($xmltext);
-
$array_e = $xml->getElementsByTagName('Encrypt');
-
$encrypt = $array_e->item(0)->nodeValue;
-
$xml = (array) simplexml_load_string(file_get_contents('php://input'), 'SimpleXMLElement', LIBXML_NOCDATA);
引用的妙用
-
//https://mp.weixin.qq.com/s?__biz=MzIyNDgxMTg0OA==&mid=2247483706&idx=1&sn=6b2ae82f64defb011d274fc7e112e111&chksm=e8080f1ddf7f860bbd4dff04b2f56ed66e56d04c7f64c16ff2311371ad31ca12baf364158337&mpshare=1&scene=1&srcid=12152cmiPUComb1gIfP1j10U&pass_ticket=b81iK1pkeLFdd9eEmU9sIrxWWPvng9ipJr9a7i9cRTaVKEUcBegn9lQ3u0lR75xX#rd
-
$catList = [
-
'1' => ['id' => 1, 'name' => '颜色', 'parent_id' => 0],
-
'2' => ['id' => 2, 'name' => '规格', 'parent_id' => 0],
-
'3' => ['id' => 3, 'name' => '白色', 'parent_id' => 1],
-
'4' => ['id' => 4, 'name' => '黑色', 'parent_id' => 1],
-
'5' => ['id' => 5, 'name' => '大', 'parent_id' => 2],
-
'6' => ['id' => 6, 'name' => '小', 'parent_id' => 2],
-
'7' => ['id' => 7, 'name' => '黄色', 'parent_id' => 1],
-
];$treeData = [];// 保存结果
-
foreach ($catList as $item) {
-
if (isset($catList[$item['parent_id']]) && ! empty($catList[$item['parent_id']])) {// 肯定是子分类
-
$catList[$item['parent_id']]['children'][] = &$catList[$item['id']];
-
} else {// 肯定是一级分类
-
$treeData[] = &$catList[$item['id']];
-
}
-
}
-
-
$treeData= [
-
['id' => 1, 'name' => '颜色', 'children' => [
-
['id' => 3, 'name' => '白色'],
-
['id' => 4, 'name' => '黑色'],
-
['id' => 7, 'name' => '黄色']
-
]],
-
['id' => 2, 'name' => '规格', 'children' => [
-
['id' => 5, 'name' => '大'],
-
['id' => 6, 'name' => '小']
-
]]
-
];
最后推荐下冯小刚新作《芳华》
这篇关于PHP 函数的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-23怎么实现安卓+php 热更新方案?-icode9专业技术文章分享
- 2024-11-22PHP 中怎么实现判断多个值是否为空、null 或者为 false?-icode9专业技术文章分享
- 2024-11-11开源 PHP 商城项目 CRMEB 二次开发和部署教程
- 2024-11-09怎么使用php在kaufland平台刊登商品?-icode9专业技术文章分享
- 2024-11-05PHP的抽象类和接口是什么,有什么区别-icode9专业技术文章分享
- 2024-11-01开源 PHP 商城项目 CRMEB 安装和使用教程
- 2024-11-01用php和mysql写无限分类,有哪几种方法-icode9专业技术文章分享
- 2024-10-31php数据分表导出时部分数据无法导出什么原因-icode9专业技术文章分享
- 2024-10-30有经验的 PHP 开发者学习一门新的编程语言,有哪些推荐的有前景的语言-icode9专业技术文章分享
- 2024-10-21php 检测图片是否篡改过-icode9专业技术文章分享