大家在对接第三方短信的时候肯定遇见过,”模板“这个概念,那么模板替换是怎么操作的呢?下面展示代码

最好的模板替换

//模版的替换
function postTempReplace($data,$str="恭喜您,注册成功,用户名:{user}密码{password},请{school}妥善保管",$start="{",$end="}")
{

$tpl_content=$str;

//接收模版的里面的变量
$replace_content= $data;
foreach ($replace_content as $key=>$val){
$tpl_content=str_replace($start.$key.$end,$val,$tpl_content);
}
return $tpl_content;




}

第一种替换方式比较简单

//模版的替换
public function postTempReplace(Request $request)
{

$tpl_content="恭喜您,注册成功,用户名:#user#密码#password#,请#school#妥善保管";

//接收模版的里面的变量
$replace_content=$request->input();

//计算短信模版中有多少需要替换的内容变量
$replace=substr_count($tpl_content,'#');

//计算几个变量 floor函数向下舍入为最接近的整数。
$number=intval(floor($replace/2));

//重复,去除,分割数组(由内到外) str_repeat去重 rtrim去除空格 explode分隔数组
$pattern=explode(',', rtrim(str_repeat("/#\w+#/,", $number),','));

//正则匹配
$tpl_content = preg_replace($pattern, $replace_content, $tpl_content , 1);

return $tpl_content;
}

替换后的内容格式:“恭喜您,注册成功,用户名:张三,密码abc,请 自己 妥善保管”

(2)第二种替换方式

public function param($content)
{
$tpl_content="恭喜您,注册成功,用户名:#user#密码#password#,请妥善保管";

$arr = explode('#', $content);

//接受要替换的变量内容
$replace_content=$request->input();

for ($i = 0; $i < count($arr); ++$i) {
// 函数返回字符串的长度
$mb = mb_strlen($arr[$i], 'gbk');
//函数返回字符串$arr[$i] 的长度
$st = strlen($arr[$i]);

if ($st == $mb) {

foreach ($replace_content as $key => $value) {

if ($arr[$i] == $key) {

$content = str_replace("#{$arr[$i]}#", htmlspecialchars($value), $content);

}
}
if ($arr[$i] == 'code') {

$content = str_replace('#code#', mt_rand(1000, 9999), $content);

}
}
}

return $content;
}