Laravel 提供了很多 辅助函数,有时候我们也需要创建自己的辅助函数。
我们把所有的『自定义辅助函数』存放于 app/Helpers/functions
.php 文件中,这里需要新建一个空文件:
在我们新增functions
.php文件之后,还需要在项目根目录下 composer.json 文件中的 autoload 选项里 files 字段加入该文件:
composer.json
{
...
"autoload": {
"psr-4": {
"App\\": "app/"
},
"classmap": [
"database/seeds",
"database/factories"
],
"files":["app/Helpers/functions.php"]
}
...
}
修改保存后运行以下命令进行重新加载文件即可:
composer dump-autoload
常用帮助函数
<?php
/**
* 通用辅助函数
*/
use Hashids\Hashids;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Validator;
/**
* 格式化特殊字符串等
* @param $strParam 需要格式化的参数
* @return string 格式化结果
*/
function replaceSpecialChar($strParam)
{
$regex = "/\/|\~|\!|\@|\#|\\$|\%|\^|\&|\*|\(|\)|\_|\+|\{|\}|\:|\<|\>|\?|\[|\]|\,|\.|\/|\;|\'|\`|\-|\=|\\\|\|/";
return preg_replace($regex, "", $strParam);
}
/**
* 格式化字节大小
* @param number $size 字节数
* @param string $delimiter 数字和单位分隔符
* @return string 格式化后的带单位的大小
*/
function get_byte($size, $delimiter = '') {
$units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
for ($i = 0; $size >= 1024 && $i < 5; $i++) $size /= 1024;
return round($size, 2) . $delimiter . $units[$i];
}
/**
* 产生随机字符串
*
* @param int $length 输出长度
* @param string $chars 可选的 ,默认为 0123456789
* @return string 字符串
*/
function get_random($length, $chars = '0123456789') {
$hash = '';
$max = strlen($chars) - 1;
for($i = 0; $i < $length; $i++) {
$hash .= $chars[mt_rand(0, $max)];
}
return $hash;
}
/**
* 作用:将xml转为array
*/
function xmlToArray($xml) {
//将XML转为array
$array_data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
return $array_data;
}
/**
* 反字符 去标签 自动加点 去换行 截取字符串
*/
function cutstr ($data, $no, $le = '') {
$data = strip_tags(htmlspecialchars_decode($data));
$data = str_replace(array("\r\n", "\n\n", "\r\r", "\n", "\r"), '', $data);
$datal = strlen($data);
$str = msubstr($data, 0, $no);