= $occurrences){ return $subject; } // replacement boundaries based on occurrence index $replace_from = $offset; $replace_to = $limit === 0 ? $occurrences : min($occurrences, $offset + $limit); // exclusive // iterate on original subject and rebuild output safely $result = ''; $search_len = strlen($search); $scan_offset = 0; $chunk_start = 0; $occurrence_index = 0; // loop through occurrences of search string while(($pos = strpos($subject, $search, $scan_offset)) !== false){ // append everything before the current occurrence $result .= substr($subject, $chunk_start, $pos - $chunk_start); // before replacement window: keep search if($occurrence_index < $replace_from){ $result .= $search; // inside replacement window: replace }elseif($occurrence_index < $replace_to){ $result .= $replace; // after replacement window }else{ if(!$delete_others){ $result .= $search; } } $occurrence_index++; $scan_offset = $pos + $search_len; $chunk_start = $scan_offset; } // append remaining tail $result .= substr($subject, $chunk_start); // return return $result; } /** * acfe_str_replace_first * * @param $search * @param $replace * @param $subject * @param $delete_others bool Should delete the other occurrences of the search string * * @deprecated since 0.9.2.6 * * @return array|mixed|string|string[] */ function acfe_str_replace_first($search, $replace, $subject, $delete_others = false){ acfe_deprecated_function('acfe_str_replace_first()', '0.9.2.6', 'Use acfe_str_replace() with offset = 0 & limit = 1'); return acfe_str_replace($subject, $search, $replace, 0, 1, $delete_others); }