How to replace a nth occurrence in a string

前端 未结 4 711
盖世英雄少女心
盖世英雄少女心 2020-12-19 04:28

I need a simple and fast solution to replace nth occurrence (placeholder) in a string.

For example, nth question mark in sql query should be replaced with a provide

4条回答
  •  旧时难觅i
    2020-12-19 04:48

    Validation on input parameter not done

     function str_replace_nth($search, $replace, $subject, $nth){
      $match_arr = explode($search,$subject);
      $match_arr = array_filter($match_arr);
    
       foreach($match_arr as $key=>$val){
    
          if($key == $nth-1){ // array index start with Zero
            $match_arr[$key] .=  $replace;
          }else{
            $match_arr[$key] .=  '?';
          }
    
       }
       return implode('',$match_arr);
    }
    

提交回复
热议问题