Last active
January 29, 2016 13:43
-
-
Save bjrnqprs/5755846 to your computer and use it in GitHub Desktop.
str_replace function with limit
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Function for performing replaces on strings that allows for the specification of a limit | |
* on the number of occurrences of $search to replace. | |
* | |
* @see http://www.php.net/manual/en/function.str-replace.php#108239 | |
* | |
* @param $search | |
* @param $replace | |
* @param $subject | |
* @param $limit | |
* @param null $count | |
* @return mixed | |
*/ | |
function str_replace_limit($search, $replace, $subject, $limit, &$count = null) { | |
$count = 0; | |
if ($limit <= 0) return $subject; | |
$occurrences = substr_count($subject, $search); | |
if ($occurrences === 0) return $subject; | |
else if ($occurrences <= $limit) return str_replace($search, $replace, $subject, $count); | |
//Do limited replace | |
$position = 0; | |
//Iterate through occurrences until we get to the last occurrence of $search we're going to replace | |
for ($i = 0; $i < $limit; $i++) | |
$position = strpos($subject, $search, $position) + strlen($search); | |
$substring = substr($subject, 0, $position + 1); | |
$substring = str_replace($search, $replace, $substring, $count); | |
return substr_replace($subject, $substring, 0, $position + 1); | |
} | |
/** | |
* Limit counting backwards. | |
* | |
* @param $search | |
* @param $replace | |
* @param $subject | |
* @param $limit | |
* @param null $count | |
* @return string | |
*/ | |
function str_replace_limit_reverse($search, $replace, $subject, $limit, &$count = null) { | |
$count = 0; | |
$search = strrev($search); | |
$replace = strrev($replace); | |
$subject = strrev($subject); | |
return strrev(str_replace_limit($search, $replace, $subject, $limit, $count)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks ;-)
But why not one single function with reverse activated with a negative $limit? (ex. -1 instead of 1)