Str_replace is a string replacement method. We all know that Strtr, strreplace, and other functions can be used to replace in PHP, but they are all replaced each time they are replaced. for example: abcabbc, if this string is used, we all know that Strtr, strreplace, and other functions can be used to replace it in PHP, but they all replace it each time. for example:
"Abcabbc": if the above function is used to replace B, all B is replaced. But what if you want to replace only one or two? See the solution below:
This is a bit interesting, and I have done similar processing before. at that time, I directly implemented it using preg_replace.
Mixed preg_replace (mixed pattern, mixed replacement, mixed subject [, int limit])
Search for matches in pattern in subject and replace them 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 can limit the number of replicas, it is very convenient to solve this problem. However, after viewing the comment on the str_replace function on php.net, you can also pick out several representative functions.
Str_replace_once
First, find the location of the keyword to be replaced, and then use the substr_replace function to replace it directly.
The code is as follows:
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
We still use preg_replace, but its parameters are more like preg_replace, and some special characters are escaped for better universality.
The code is 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 );
}
?>
Secret "abcabbc", if this string uses the above...