Home  >  Article  >  Backend Development  >  【求解】字符串生成数组根据自定义规则输出解决方法

【求解】字符串生成数组根据自定义规则输出解决方法

WBOY
WBOYOriginal
2016-06-13 13:16:041067browse

【求解】字符串生成数组根据自定义规则输出
字符串生成数组根据自定义规则输出
根据函数split_array("百度#http://www.baidu.com/\n百度#http://www.baidu.com/\n","\n|#","{0}");
要求输出
百度
百度

这个函数怎么写?

------解决方案--------------------
这样写

PHP code
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>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn