【求解】字符串生成数组根据自定义规则输出
字符串生成数组根据自定义规则输出
根据函数split_array("百度#http://www.baidu.com/\n百度#http://www.baidu.com/\n","\n|#","{0}");
要求输出
百度
百度
这个函数怎么写?
------解决方案--------------------
这样写
split_array("百度#http://www.baidu.com/\n百度#http://www.baidu.com/\n","\n|#","<a href="%7B1%7D">{0}</a>");
function split_array($str, $pattern, $template) {
$cnt = substr_count($template, '{'); //统计模板中替换位置的个数
$tmp = preg_split('/'.$pattern.'/', $str, -1, PREG_SPLIT_NO_EMPTY); //按规则切割数据
$m = count($tmp) % $cnt;
if($m) $tmp = array_slice($tmp, 0, -$m); //除去多余的数据
$tmp = array_chunk($tmp, $cnt); //将数据分组
$r = array();
foreach($tmp as $m) {
$t = $template;
foreach($m as $i=>$v) {
$t = str_replace("{{$i}}", $v, $t);
}
$r[] = $t;
}
echo join('<br>', $r);
} <div class="clear"></div>
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号