As we all know, in PHP, Strtr,strreplace and other functions can be used to replace, but they are all replaced each time, for example:
"Abcabbc", this string is replaced with B by using the function above to replace it, but what if you want to replace only one or two? Look at the following solution:
This is a more interesting question, just before I did a similar deal, when I was directly using preg_replace to achieve.
Mixed preg_replace (mixed pattern, mixed replacement, mixed subject [, int limit])
Searches the subject for a match in pattern mode and replaces it with replacement. If limit is specified, only the limit match is substituted, and if limit is omitted or the value is-1, all occurrences are replaced.
Because the fourth parameter of Preg_replace can be used to limit the number of substitutions, this is a convenient way to handle this problem. But after looking at the function comment on the php.net on Str_replace, you can also pick out a few representative functions from it.
Str_replace_once
The idea is first to find the location of the keyword to be replaced, and then use the Substr_replace function to replace it directly.
Copy Code code as follows:
<?php
function Str_replace_once ($needle, $replace, $haystack) {
Looks for the ' occurence ' $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
Or the use of preg_replace, but its parameters are more like preg_replace, and some special characters have been escaped processing, the versatility is better.
Copy Code code as follows:
?
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);
}
?>