PHP 函数

2021/6/15 12:21:26

本文主要是介绍PHP 函数,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

本文记录些有用的函数

过滤掉emoji表情

  1. function filterEmoji($str)

  2. {

  3.    $str = preg_replace_callback(

  4.            '/./u',

  5.            function (array $match) {

  6.                return strlen($match[0]) >= 4 ? '' : $match[0];

  7.            },

  8.            $str);

  9.  

  10.     return $str;

  11. }

获取 ip

  1. function get_ip_address(){

  2.    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){

  3.        if (array_key_exists($key, $_SERVER) === true){

  4.            foreach (explode(',', $_SERVER[$key]) as $ip){

  5.                $ip = trim($ip); // just to be safe

  6.                if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false){

  7.                    return $ip;

  8.                }

  9.            }

  10.        }

  11.    }

  12. }

导出 excel

  1. function exportData($fileName,$content){

  2.        header("Content-type: text/html; charset=utf-8");

  3.        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");

  4.        header("Content-Type: application/vnd.ms-execl");

  5.        header("Content-Type: application/force-download");

  6.        header("Content-Type: application/download");

  7.        header("Content-Disposition: attachment; filename=".$fileName);

  8.        header("Content-Transfer-Encoding: binary");

  9.        header("Pragma: no-cache");

  10.        header("Expires: 0");

  11.        echo $content;exit;

  12.    }

安全 base64

  1. //Base64编码原理与应用http://blog.xiayf.cn/2016/01/24/base64-encoding/

  2. function urlsafe_base64_encode($data)

  3.    {

  4.        return strtr(base64_encode($data), ['+' => '-', '/' => '_', '=' => '']);

  5.    }

  6. function urlsafe_base64_decode($data, $strict = false)

  7.    {

  8.        return base64_decode(strtr($data, '-_', '+/'), $strict);

  9.    }

  10. function safeStrlen($str)

  11.    {

  12.        if (function_exists('mb_strlen')) {

  13.            return mb_strlen($str, '8bit');

  14.        }

  15.        return strlen($str);

  16.    }

httpbuildquery bug

  1. //重温PHP手册http://www.powerxing.com/php-review-oop/

  2. $arr=[

  3.       "x" => false,

  4.       "y" => "",

  5.       "z" => null

  6.   ];

  7. http_build_query($arr)

  8. => "x=0&y="  

  9. foreach($arr as $k=>$v){$r.=$k.'='.$v.'&';}

解析命令行

  1. unction exp_command($str)

  2. {

  3.    // 正则表达式

  4.    $regEx = '#(?:(?<s>[\'"])?(?<v>.+?)?(?:(?<!\\\\)\k<s>)|(?<u>[^\'"\s]+))#';

  5.    // 匹配所有

  6.    if(!preg_match_all($regEx, $str, $exp_list)) return false;

  7.    // 遍历所有结果

  8.    $cmd = array();

  9.    foreach ($exp_list['s'] as $id => $s) {

  10.        // 判断匹配到的值

  11.        $cmd[] = empty($s) ? $exp_list['u'][$id] : $exp_list['v'][$id];

  12.    }

  13.    return $cmd;

  14. }

  15. // 命令行字符串

  16. $str = 'cmd -n "rel\'o\"a d" \'te"s\' t\'    upload ""';

  17. $cmd = exp_command($str);

  18. print_r($cmd);

  19. /* 打印输出结果

  20. Array

  21. (

  22.    [0] => cmd

  23.    [1] => -n

  24.    [2] => rel'o\"a d

  25.    [3] => te"s

  26.    [4] => t

  27.    [5] => upload

  28.    [6] =>

  29. )

  30. */

求两个经纬度之间的距离

  1. function getDistance($aLng, $aLat, $bLng, $bLat)

  2. {

  3.    //将角度转为狐度https://www.lvtao.net/dev/1899.html

  4.    $aLng    = deg2rad($aLng);

  5.    $aLat    = deg2rad($aLat);

  6.    $bLng    = deg2rad($bLng);

  7.    $bLat    = deg2rad($bLat);

  8.    $lngDiff = $aLng - $bLng;

  9.    $latDiff = $aLat - $bLat;

  10.    $diff = 2 * asin(sqrt(pow(sin($latDiff / 2), 2) + cos($aLat) * cos($bLat) * pow(sin($lngDiff / 2), 2))) * 6378.137 * 1000;

  11.    return $diff;

  12. }

  13.  

  14. echo getDistance(36.059907, 120.300687, 36.019983, 120.296447);

多条数据,根据权限随机展示

  1. function getConsultant()

  2. {

  3.    $data = array(

  4.      array('name'=>'user1','weights'=>1),

  5.      array('name'=>'user2','weights'=>2),

  6.      array('name'=>'user3','weights'=>3),

  7.      array('name'=>'user4','weights'=>4)

  8.    );

  9.    $weight = 0;

  10.    $users = array();

  11.    foreach ($data as $one) {

  12.        $oneWeight = (int)$one['weights'] ? $one['weights'] : 1;

  13.        $weight += $oneWeight;

  14.        for ($i = 0; $i < $oneWeight; $i ++) {

  15.            $users[] = $one;

  16.        }

  17.    }

  18.    return $users[rand(0, $weight-1)];

  19. }

PHP多进程同时写文件

  1. function ffwrite($filename,$content) {

  2.      $file = fopen("$filename","a");

  3.      while(1) {

  4.         if (flock($file,LOCK_EX))

  5.         {

  6.            fwrite($file,$content);

  7.            flock($file,LOCK_UN);

  8.            fclose($file);

  9.            break;

  10.            } else {

  11.            usleep(1000);

  12.         }

  13.      }

  14.   }

随机汉字

  1. function genstr($num)

  2.   {

  3.      for($i=0;$i<=$num;$i++)

  4.      {

  5.         $str .= '&#'.rand(19968, 40869).';';

  6.      }

  7.  

  8.      return mb_convert_encoding($str, "UTF-8", "HTML-ENTITIES");

  9.   }

  10.   echo genstr(mt_rand(1,8));

  11. function genstr2($num)

  12.   {

  13.      for($i=0;$i<=$num;$i++)

  14.      {

  15.         $str .= chr(rand(0xB0,0xF7)).chr(rand(0xA1,0xFE));

  16.      }

  17.  

  18.      return $str;

  19.   }

  20.   echo genstr2(mt_rand(1,8));

转换字节

  1. function convert($size)

  2.   {

  3.      $unit=array('b','kb','mb','gb','tb','pb');

  4.      return @round($size/pow(1024,($i=floor(log($size,1024)))),2).$unit[$i];

  5.   }

  6. echo convert(memory_get_usage(true));

一致性hash

  1. function get_hash($str, $num=10){

  2.  $crc = crc32($str);

  3.  $nu = $crc % $num;

  4.  return $nu;

  5. }

  6.  

  7. function genstr($num) {

  8.  return substr(str_shuffle('abcdefghijklmnupqrstuvwxyz'), 0, $num);

  9. }

  10.  

  11. for ($i=1; $i<10000000; $i++) {

  12.  $str = genstr(5);

  13.  $crc = crc32($str);

  14.  $nu = get_hash($str);;

  15.  if (isset($count[$nu])) {

  16.    $count[$nu]++;

  17.  } else {

  18.    $count[$nu]=1;

  19.  }

  20. }

  21. print_r($count);

Base62

  1. class Base62 {

  2.  

  3.    private $string = "vPh7zZwA2LyU4bGq5tcVfIMxJi6XaSoK9CNp0OWljYTHQ8REnmu31BrdgeDkFs";

  4.  

  5.    public function base62_encode($str) {

  6.        $out = '';

  7.        for($t=floor(log10($str)/log10(62)); $t>=0; $t--) {

  8.            $a = floor($str / pow(62, $t));

  9.            $out = $out.substr($this->string, $a, 1);

  10.            $str = $str - ($a * pow(62, $t));

  11.        }  

  12.        return $out;

  13.    }  

  14.  

  15.    public function base62_decode($str) {

  16.        $out = 0;

  17.        $len = strlen($str) - 1;

  18.        for($t=0; $t<=$len; $t++) {

  19.            $out = $out + strpos($this->string, substr($str, $t, 1)) * pow(62, $len - $t);

  20.        }  

  21.        return substr(sprintf("%f", $out), 0, -7);

  22.    }  

  23. }

  24. $str = 1234567;

  25. $object = new Base62();

  26. echo $object->base62_encode($str) . "\n";

  27. echo $object->base62_decode($object->base62_encode($str)) . "\n";

字符截取

  1. function  substr_utf8($str,$start,$length){  

  2.    return implode("",array_slice(preg_split("//u",$str,-1,PREG_SPLIT_NO_EMPTY),$start,$length));  

  3. }  

  4. echo substr_count($str,'你');

用DOMXpath加载DOM

  1. //创建一个DomDocument对象,用于处理一个HTML

  2. $dom = new DOMDocument();

  3. //从一个字符串加载HTML

  4. @$dom->loadHTML($html);

  5. //使该HTML规范化

  6. $dom->normalize();

  7.  

  8. //用DOMXpath加载DOM,用于查询

  9. $xpath = new DOMXPath($dom);

  10. #获取所有的a标签的地址

  11. $hrefs = $xpath->evaluate("/html/body//a//@href");

  12.  

  13. for ($i = 0; $i < $hrefs->length; $i++) {

  14.    $href = $hrefs->item($i);

  15.    $linktext = $href->nodeValue;

  16.    echo $linktext;

  17.    echo "<BR>";

  18.  

  19. }

计算两个以YYYY-MM-DD为格式的日期,相差几天

  1. function getChaBetweenTwoDate($date1,$date2){

  2.  

  3.    $Date_List_a1=explode("-",$date1);

  4.    $Date_List_a2=explode("-",$date2);

  5.  

  6.    $d1=mktime(0,0,0,$Date_List_a1[1],$Date_List_a1[2],$Date_List_a1[0]);

  7.  

  8.    $d2=mktime(0,0,0,$Date_List_a2[1],$Date_List_a2[2],$Date_List_a2[0]);

  9.  

  10.    $Days=round(($d1-$d2)/3600/24);

  11.  

  12.    return $Days;

  13. }

  14.  

  15. echo getChaBetweenTwoDate('2010-08-11','2010-08-16');

static

  1. class ParentClass {

  2.    public static function name()

  3.    {

  4.        return __CLASS__;

  5.    }

  6. public static function create()

  7.    {

  8.        return new static();

  9.    }

  10.    public static function test()

  11.    {

  12.        return self::name(); //改为static::name() 就可以了

  13.    }

  14. }

  15. class ChildClass extends ParentClass {

  16.    public static function name()

  17.    {

  18.        return __CLASS__;

  19.    }

  20. }

  21. echo ChildClass::test();

并发请求

  1. $requestUrls = [];

  2. for ($i=0; $i<10; $i++) {

  3.    array_push($requestUrls, 'http://baidu.com');

  4. }

  5. $mh = curl_multi_init();

  6. $chs = [];

  7. foreach ($requestUrls as $url) {

  8.    $chs[] = $ch = curl_init();

  9.    curl_setopt($ch, CURLOPT_URL, $url);

  10.    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

  11.    curl_setopt($ch, CURLOPT_TIMEOUT, 3000);

  12.    curl_setopt($ch, CURLOPT_NOSIGNAL, true);

  13.    curl_setopt($ch, CURLOPT_HEADER, 0);

  14.    curl_setopt($ch, CURLOPT_PROXY, '127.0.0.1:8888');

  15.    curl_multi_add_handle($mh, $ch);

  16. }

  17. do {

  18.    curl_multi_exec($mh, $running);

  19.    curl_multi_select($mh);

  20. } while ($running > 0);

  21. $res = [];

  22. foreach ($chs as $k => $ch) {

  23.    $res[] = curl_multi_getcontent($ch);

  24.    curl_multi_remove_handle($mh, $ch);

  25.    echo $k . ' success' . PHP_EOL;

  26. }

  27. curl_multi_close($mh);

几天后日期

  1. function rangeDaysAfterTimeStamp($startTimestamp, $daysNum = 1)

  2.    {

  3.        $range = [];

  4.  

  5.        do {

  6.            $range[] = date('Y-m-d 00:00:00', $startTimestamp + (-- $daysNum) * 86400);

  7.        } while ($daysNum);

  8.  

  9.        rsort($range);

  10.  

  11.        return $range;

  12.    }

  13. >>> rangeDaysAfterTimeStamp(strtotime('2017-11-11'),7)

  14. => [

  15.       "2017-11-17 00:00:00",

  16.       "2017-11-16 00:00:00",

  17.       "2017-11-15 00:00:00",

  18.       "2017-11-14 00:00:00",

  19.       "2017-11-13 00:00:00",

  20.       "2017-11-12 00:00:00",

  21.       "2017-11-11 00:00:00"

  22.   ]

  23. function rangeDays($beginTimestamp, $endTimestamp)

  24.    {

  25.        $beginTimestamp = strtotime(date('Y-m-d', $beginTimestamp));

  26.        $endTimestamp = strtotime(date('Y-m-d', $endTimestamp));

  27.  

  28.        $range = [];

  29.        $i = 0;

  30.  

  31.        do {

  32.            $time = $beginTimestamp + $i * 86400;

  33.            $range[] = date('Y-m-d 00:00:00', $time);

  34.            $i++;

  35.        } while ($time < $endTimestamp);

  36.  

  37.        return $range;

  38.    }

下载文件

  1. $ch = curl_init();

  2.  

  3.    $fp=fopen('./girl.jpg', 'w');

  4.  

  5.    curl_setopt($ch, CURLOPT_URL, "http://远程服务器地址马赛克/girl.jpg");

  6.    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);

  7.    curl_setopt($ch, CURLOPT_FILE, $fp);

  8.  

  9.    $output = curl_exec($ch);

  10.    $info = curl_getinfo($ch);

  11.  

  12.    fclose($fp);

  13.  

  14.    $size = filesize("./girl.jpg");

  15.    if ($size != $info['size_download']) {

  16.        echo "下载的数据不完整,请重新下载";

  17.    } else {

  18.        echo "下载数据完整";

  19.    }

redis 消息推送

  1. // ini_set(‘default_socket_timeout’, -1); https://github.com/TIGERB/easy-tips/blob/master/redis/subscribe-publish/subscribe.php

  2.  $redis = new \Redis();

  3.  $redis->pconnect('127.0.0.1', 6379);

  4.  //订阅

  5.  echo "订阅msg这个频道,等待消息推送... \n";

  6.  $redis->subscribe(['msg'], 'callfun');

  7.  function callfun($redis, $channel, $msg)

  8.  {

  9.   print_r([

  10.     'redis'   => $redis,

  11.     'channel' => $channel,

  12.     'msg'     => $msg

  13.   ]);

  14.  }

  15. $redis->publish('msg', '来自msg频道的推送');

  16.  echo "msg频道消息推送成功~ \n";

  17.  $redis->close();

xml

  1. $format = <<<XML

  2. <xml>

  3. <Encrypt><![CDATA[%s]]></Encrypt>

  4. <MsgSignature><![CDATA[%s]]></MsgSignature>

  5. <TimeStamp>%s</TimeStamp>

  6. <Nonce><![CDATA[%s]]></Nonce>

  7. </xml>

  8. XML;

  9. $xml = new \DOMDocument();

  10.            $xml->loadXML($xmltext);

  11.            $array_e = $xml->getElementsByTagName('Encrypt');

  12.            $encrypt = $array_e->item(0)->nodeValue;

  13. $xml = (array) simplexml_load_string(file_get_contents('php://input'), 'SimpleXMLElement', LIBXML_NOCDATA);

引用的妙用

  1. //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

  2. $catList = [

  3.    '1' => ['id' => 1, 'name' => '颜色', 'parent_id' => 0],

  4.    '2' => ['id' => 2, 'name' => '规格', 'parent_id' => 0],

  5.    '3' => ['id' => 3, 'name' => '白色', 'parent_id' => 1],

  6.    '4' => ['id' => 4, 'name' => '黑色', 'parent_id' => 1],

  7.    '5' => ['id' => 5, 'name' => '大', 'parent_id' => 2],

  8.    '6' => ['id' => 6, 'name' => '小', 'parent_id' => 2],

  9.    '7' => ['id' => 7, 'name' => '黄色', 'parent_id' => 1],

  10. ];$treeData = [];// 保存结果

  11. foreach ($catList as $item) {

  12.    if (isset($catList[$item['parent_id']]) && ! empty($catList[$item['parent_id']])) {// 肯定是子分类

  13.        $catList[$item['parent_id']]['children'][] = &$catList[$item['id']];

  14.    } else {// 肯定是一级分类

  15.        $treeData[] = &$catList[$item['id']];

  16.    }

  17. }

  18.  

  19. $treeData= [

  20.    ['id' => 1, 'name' => '颜色', 'children' => [

  21.        ['id' => 3, 'name' => '白色'],

  22.        ['id' => 4, 'name' => '黑色'],

  23.        ['id' => 7, 'name' => '黄色']

  24.    ]],

  25.    ['id' => 2, 'name' => '规格', 'children' => [

  26.        ['id' => 5, 'name' => '大'],

  27.        ['id' => 6, 'name' => '小']

  28.    ]]

  29. ];

 

最后推荐下冯小刚新作《芳华》

watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=

 



这篇关于PHP 函数的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程