今天需要電話等機敏資料隱碼顯示,所以建立了一個function,方便以後可以使用。
replace_symbol(要處理的字串,取代成的字,前面顯示幾個字,後面顯示幾個字);
使用方式:
echo replace_symbol(“123456789”,’*’,3,3);
結果就會是 123***789
function replace_symbol($string, $symbol, $begin_num = 0, $end_num = 0) { $length = strlen($string); $begin_num = (int) $begin_num; $end_num = (int) $end_num; $str1 = substr( $string ,0, $begin_num ); $str2 = substr( $string , -$end_num ); $reduce_num = $length - $begin_num - $end_num; $str3 =""; for ($i = 0; $i <= $reduce_num; $i++) { $str3 .= $symbol; } return $str1.$str3.$str2; }
但是如果您想要用的是中文,那我們Function就必須改變一下了
因為substr對中文切割,會把中文算是兩個字。
所以以下我們改用mb_substr
function replace_symbol($string, $symbol, $begin_num = 0, $end_num = 0) { $length = strlen($string); $begin_num = (int) $begin_num; $end_num = (int) $end_num; $str1 = mb_substr( $string ,0, $begin_num,"utf-8" ); $str2 = mb_substr( $string , -$end_num,"utf-8" ); $reduce_num = $length - $begin_num - $end_num; $str3 =""; for ($i = 0; $i <= $reduce_num; $i++) { $str3 .= $symbol; } return $str1.$str3.$str2; }