PHP 字符串截取和随机字符串函数封装
方文锋
2020-03-30 08:46:43
1038
首页学习PHP
/**
*把字符串分割为数组(一维数组)
*@$str string 分割的字符串
*@$charset string 字符串编码
*/
function str_cut($str,$charset='utf-8'){
$re['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
$re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
$re['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
$re['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
preg_match_all($re[$charset], $str, $match);
return $match[0];
}
//返回随机字符串
function randomString($l=5,$mode="n",$config=[],$charset="utf-8"){
$C=[
"n" => "0123456789"
,"s" => "abcdefghijklmnopqrstuvwxyz"
,"S" => "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
,"ns" => "0123456789abcdefghijklmnopqrstuvwxyz"
,"nS" => "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
,"sS" => "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
,"nsS" => "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
,"all" => "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_^+*=|,.~!@#"
];
if (is_array($config)) {
foreach ($config as $key => $value) {
$C[$key]=str_cut($value, $charset);
}
}
$mode= empty($C[$mode]) ? "n" : $mode ;
$str=""; if(is_array($C[$mode]) && count($C[$mode])>0 ){
for($i=0,$len=count($C[$mode]);$i<$l;$i++){
$str.=$C[$mode][mt_rand(0,$len-1)];
}
}
else{
for($i=0,$len=strlen($C[$mode]);$i<$l;$i++){
$str.=$C[$mode][mt_rand(0,$len-1)];
}
}
return $str;
}
/**
* 字符串截取
* @$str string 要截取的字符串
* @$start number 要截取的开始位置,从0开始
* @$length nunber 截取的长度
* @$charset string 字符串编码
*/
function msubstr($str, $start = 0, $length, $charset = "utf-8", $suffix = true)
{
if (function_exists("mb_substr"))
$slice = mb_substr($str, $start, $length, $charset);
elseif (function_exists('iconv_substr')) {
$slice = iconv_substr($str, $start, $length, $charset);
if (false === $slice) {
$slice = '';
}
} else {
$re['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
$re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
$re['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
$re['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
preg_match_all($re[$charset], $str, $match);
$slice = join("", array_slice($match[0], $start, $length));
}
//字数不满不添加...
$count = mb_strlen($str, 'utf-8');
if ($count > $length) {
return $suffix ? $slice . '......' : $slice;
} else {
return $slice;
}
}