public function index() { //数据表随机取出n条数据 $data = DB::select(" SELECT school_id,school_name FROM `pub_school` WHERE school_id >= ( SELECT floor( RAND() * (SELECT MAX(school_id) FROM `pub_school`) ) ) ORDER BY school_id LIMIT 12");
foreach ($data as $k => $v) { $strlen = mb_strlen($v->school_name, 'utf-8'); //计算长度 $firstStr = mb_substr($v->school_name, 0, 1, 'utf-8'); //截取第一个汉字 $lastStr = mb_substr($v->school_name, -1, 1, 'utf-8'); //截取最后一个汉字 //str_repeat 重复 $data[$k]->school_name = $strlen <= 4 ? $firstStr . str_repeat('*', mb_strlen($v->school_name, 'utf-8') - 1) : $firstStr . str_repeat("*", $strlen - 2) . $lastStr; } return $data; }
原数据:
替换后数据: