PHP知识
自增自减及运算符的优先级
// 后++和后--先返回值再递加或递减;自增和自减运算符优先于算术运算符。
$a = 5;
echo $a---$a--;
进制
// 0123在PHP中会被当做8进制处理,转换成十进制83,所以输出false.
var_dump(0123 === 123);
弱类型
// if条件中0会当做false处理 所以会输出else下的内容,正确的判断:if(strpos($str1,$str2)!==false)
$str1 = 'abcdefg';
$str2 = 'abc';
if (strpos($str1, $str2)) {
echo $str2.'在'.$str1.'中';
} else {
echo $str2.'不在'.$str1.'中';
}
正则
// ^ 和 $ 定位符分别指字符串的开始和结束位置,本题的字符串开始位置是Eat所以输出0
$str = 'Eat to live, but not live to eat';
echo preg_match("/^to/", $str);
功能代码
1.遍历一个文件夹下的所有文件和子文件夹
/**
* 遍历一个文件夹下的所有文件和子文件夹
* @param string $dir 目录
* @return array
*/
function read_file($dir)
{
if (!is_dir($dir)) {
die('this is not a directory');
}
$arr = array();
if($dh = opendir($dir)){
while (($file = readdir($dh)) !== false) {
// 判断是否有文件或子文件夹
if ($file !='.' && $file !='..') {
// 当有子文件夹的情况
if (is_dir($dir.'/'.$file)) {
// 递归 获取子文件夹下的文件
$arr[$file] = read_file($dir.'/'.$file);
} else {
$arr[] = $file;
}
}
}
closedir($dh);
}
return $arr;
}
2.获取文件的后缀名
$url = 'www/test/index.html?a=1&b=2';
// 解法一
$re = parse_url($url);
$path = explode('.', $re['path']);
$res = end($path);
// 解法二
$re = strstr($url, '.');
$res = substr($re, 1, 4);
- 多进程写入文件
$file = fopen('test.txt', 'w+');
if (flock($file, 'LOCK_EX')) {
// 获取写锁定 写入数据
fwrite($file, 'some thing');
// 解除锁定
flock($file, 'LOCK_UN');
} else {
echo 'Fail to lock';
}
fclose($file);
4.创建多级目录
/**
* 创建多级目录
* @param string $dir 目录
* @param int $mode 权限
*/
function create_dir($dir, $mode=0777)
{
if (is_dir($dir)) {
echo 'Directory already exists';
}
if (mkdir($dir, $mode, true)) {
echo 'Directory creation successful';
} else {
echo 'Directory creation fail';
}
}
5.获取给定月份的上一月最后一天
/**
* @param string $t 日期
*/
function getTime($t='')
{
if ($t != '') {
$date = strtotime($t);
} else {
$date = time();
}
// 方法一、确定当月的天数然后减去,自然就是上月的最后一天
$day = date('d', $date);
$re = date('Y-m-d', strtotime("-{$day} days", $date));
// 方法二、先获取上月的时间,再确定最后一天
$lastMonth = strtotime('last month', $date);
$re = date('Y-m-t', $lastMonth);
echo $re;
}
getTime('2018-10-5');
6.解决strtoupper()或strtolower()中文乱码问题
/**
* 解决 strtoupper()中文乱码问题
* @param string $data 待转换的字符串
* @return string
*/
function strUpper($data)
{
$arr = str_split($data, 1); // 按字节拆分成数组
$re = '';
foreach ($arr as $v) {
$v = ord($v); // 转换成ASCII码
if ($v >= 97 && $v <= 122) { // 确定小写字母范围
$v -= 32; // 转换成大写字母 65-90
}
$re .= chr($v); // 转换成字符
}
return $re;
}
$str = strUpper('a中你继续F@#$%^&*(BMDJFDoalsdkfjasl');
var_dump($str);
7.发一个随机红包,100块钱给10个人。每个人最多12块钱,最少6块钱。怎么分?
/*设sum=100,n=10,则题目可以得到以下结论6n <= sum <= 12n。
设randNum为随机红包的大小,则可以推出6(n-1) <= (sum-randNum) <= 12(n-1)*/
function redPacket()
{
$n = 10;
$sum = 100;
$result = [];
while ($n > 1) {
$randNum = mt_rand(6, 12) ;
if (($sum - $randNum) >= 6 * ($n - 1) && ($sum - $randNum) <= 12 * ($n - 1)) {
$n -= 1;
$sum -= $randNum;
$result[] = $randNum;
}
}
$result[] = $sum;
print_r($result);
}
redPacket();