当我们需要生成一个随机名字,临时密码等字符串时可以用到此PHP函数
function generateRandomString($length = 10) { $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $randomString = ''; for ($i = 0; $i < $length; $i++) { $randomString .= $characters[rand(0, strlen($characters) - 1)]; } return $randomString; }
echo generateRandomString(20);
这个题我是第一次遇到,所以手写对我来说基本不可能,因为我遇到问题必须在机子上反复调试才可能得到最终答案,既然遇到了回来还是在电脑上试着写了一下,如有不足或者更简单的方法,欢迎指正。这个题的目的就是写一个函数找出字符串中对称的部分,然后获取符合条件中最长的那个字符串,比如字符串‘ssabcddcba’,那么符合条件的就是‘abcddcba’,下面直接上代码。
$str='aa6aaslolsbcdeggedcbaiokabccbanh'; function getMaxStr($str){ $s_data=str_split($str); $row=[]; foreach($s_data as $key=>$vol){ foreach($s_data as $k=>$v){ if($k<$key) continue; if($vol==$v && $key!=$k){ if(($key+$k)==1){ $row[]=substr($str,$key,2); }else{ $px=$key==0?$k+1:$k-$key; $px=($px%2)==0?$px:($k-$key+1); $px=$px/2; for($s=1;$s<$px;$s++){ if($s_data[$key+$s]!=$s_data[$k-$s]) continue 2; } $row[]=substr($str,$key,($k-$key+1)); } } } } return $row; } $r=getMaxStr($str); print_r($r);
Array ( [0] => aa [1] => aa6aa [2] => a6a [3] => aa [4] => slols [5] => lol [6] => bcdeggedcb [7] => cdeggedc [8] => degged [9] => egge [10] => gg [11] => abccba [12] => bccb [13] => cc )
很多时候我们传图片由于图片过大需要压缩,但是常常压缩后图片会缺失不完整,这不是我们想要的效果,这个方法可以达到比较满意的效果,至少本人使用非常好,在减少图片大小的前提下能够保证图片的完整性。
//$imgsrc 图片地址 //$imgdst 压缩后地址 function compress_img($imgsrc, $imgdst) { list($width, $height, $type) = getimagesize($imgsrc); $new_width = $width;//压缩后的图片宽 $new_height = $height;//压缩后的图片高 if($width >= 600){ $per = 600 / $width;//计算比例 $new_width = $width * $per; $new_height = $height * $per; } switch ($type) { case 1: header('Content-Type:image/gif'); $image_wp = imagecreatetruecolor($new_width, $new_height); $image = imagecreatefromgif($imgsrc); imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height); //90代表的是质量、压缩图片容量大小 imagejpeg($image_wp, $imgdst, 90); imagedestroy($image_wp); imagedestroy($image); break; case 2: header('Content-Type:image/jpeg'); $image_wp = imagecreatetruecolor($new_width, $new_height); $image = imagecreatefromjpeg($imgsrc); imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height); //90代表的是质量、压缩图片容量大小 imagejpeg($image_wp, $imgdst, 90); imagedestroy($image_wp); imagedestroy($image); break; case 3: header('Content-Type:image/png'); $image_wp = imagecreatetruecolor($new_width, $new_height); $image = imagecreatefrompng($imgsrc); imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height); //90代表的是质量、压缩图片容量大小 imagejpeg($image_wp, $imgdst, 90); imagedestroy($image_wp); imagedestroy($image); break; } }
PHP加密和解密函数可以用来加密一些有用的字符串存放在数据库里,并且通过可逆解密字符串,该函数使用了base64和MD5加密和解密。
function encryptDecrypt($key, $string, $decrypt) { if($decrypt) { $decrypted = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode($string), MCRYPT_MODE_CBC, md5(md5($key))), "12"); return $decrypted; } else { $encrypted = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $string, MCRYPT_MODE_CBC, md5(md5($key)))); return $encrypted; } }
//以下是将字符串“素材牛(www.sucainiu.com)”分别加密和解密 //加密: echo encryptDecrypt('password', '素材牛(www.sucainiu.com)',0); //解密: echo encryptDecrypt('password', 'KMQY7BhdFF8oKh/yr3eekMB4tE8vbshodya9WnRpjVc=',1);
以下函数可以快速获取文件的扩展名即后缀。
function getExtension($filename){ $myext = substr($filename, strrpos($filename, '.')); return str_replace('.','',$myext); }
$filename = '我的文档.doc'; echo getExtension($filename);
以下使用的函数可以获取文件的大小,并且转换成便于阅读的KB,MB等格式。
function formatSize($size) { $sizes = array(" Bytes", " KB", " MB", " GB", " TB", " PB", " EB", " ZB", " YB"); if ($size == 0) { return('n/a'); } else { return (round($size/pow(1024, ($i = floor(log($size, 1024)))), 2) . $sizes[$i]); } }
$thefile = filesize('test_file.mp3'); echo formatSize($thefile);
有时我们需要将字符串、模板标签替换成指定的内容,可以用到下面的函数:
function stringParser($string,$replacer){ $result = str_replace(array_keys($replacer), array_values($replacer),$string); return $result; }
$string = 'The {b}anchor text{/b} is the {b}actual word{/b} or words used {br}to describe the link {br}itself'; $replace_array = array('{b}' => '<b>','{/b}' => '</b>','{br}' => '<br />'); echo stringParser($string,$replace_array);
如果你想列出目录下的所有文件,使用以下代码即可:
function listDirFiles($DirPath){ if($dir = opendir($DirPath)){ while(($file = readdir($dir))!== false){ if(!is_dir($DirPath.$file)) { echo "filename: $file"; } } } }
listDirFiles('home/some_folder/');
以下函数可以获取当前页面的URL,不管是http还是https。
function curPageURL() { $pageURL = 'http'; if (!empty($_SERVER['HTTPS'])) {$pageURL .= "s";} $pageURL .= "://"; if ($_SERVER["SERVER_PORT"] != "80") { $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"]; } else { $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"]; } return $pageURL; }
echo curPageURL();
有时我们不想让浏览器直接打开文件,如PDF文件,而是要直接下载文件,那么以下函数可以强制下载文件,函数中使用了application/octet-stream头类型。
function download($filename){ if ((isset($filename))&&(file_exists($filename))){ header("Content-length: ".filesize($filename)); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename="' . $filename . '"'); readfile("$filename"); } else { echo "Looks like file does not exist!"; } }
download('/down/test_45f73e852.zip');