str_replace method that replaces a string only once

  • 2020-06-01 08:25:44
  • OfStack

As we all know, in PHP, Strtr,strreplace and other functions can be substituted, but every time they are replaced, they are completely replaced. For example:
"abcabbc", this string if you use the function above to replace the b, then it will replace all of them, but what if you want to replace only one or two? Here's the solution:
This is a bit of an interesting question, and I've done something similar before, when I implemented it directly using preg_replace.

mixed preg_replace ( mixed pattern, mixed replacement, mixed subject [, int limit] )
Search subject for a match of the pattern pattern and replace it with replacement. If limit is specified, only limit matches are replaced; if limit is omitted or its value is -1, all matches are replaced.
Because the fourth parameter of preg_replace implements a limit on the number of substitutions, this problem can be handled conveniently. However, after looking at the php.net function reviews for str_replace, you can actually pick out a few representative functions.

str_replace_once
The idea is to first find the location of the keyword to be replaced, and then directly replace it with the substr_replace function.


<?php 
function str_replace_once($needle, $replace, $haystack) { 
// Looks for the first occurence of $needle in $haystack 
// and replaces it with $replace. 
$pos = strpos($haystack, $needle); 
if ($pos === false) { 
return $haystack; 
} 
return substr_replace($haystack, $replace, $pos, strlen($needle)); 
} 
?> 

str_replace_limit
Again, preg_replace is used, but its parameters are more like preg_replace, and some special characters are escaped, which makes it more universal.


<? 
function str_replace_limit($search, $replace, $subject, $limit=-1) { 
// constructing mask(s)... 
if (is_array($search)) { 
foreach ($search as $k=>$v) { 
$search[$k] = '`' . preg_quote($search[$k],'`') . '`'; 
}
} 
else { 
$search = '`' . preg_quote($search,'`') . '`'; 
} 
// replacement 
return preg_replace($search, $replace, $subject, $limit); 
} 
?> 


Related articles: