PHP字符串截取替换*

2021/8/25 1:06:15

本文主要是介绍PHP字符串截取替换*,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

 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;
    }

 

原数据:

 

 

 

 

替换后数据:

 



这篇关于PHP字符串截取替换*的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程