This article mainly introduces how php can be replaced only once or only N times. A simple example is used to introduce the topic. For more information, see Strtr in PHP, all strreplace and other functions can be used for replacement, but they all replace 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.
Method 1: str_replace_once
IdeasFirst, locate the location of the keyword to be replaced, and then use the substr_replace function to replace it directly.
<?phpfunction 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) {// Nothing foundreturn $haystack;}return substr_replace($haystack, $replace, $pos, strlen($needle));}?>
Method 2: str_replace_limit
IdeasWe still use preg_replace, but its parameters are more like preg_replace, and some special characters are escaped for better universality.
<?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,'`') . '`';}// replacementreturn preg_replace($search, $replace, $subject, $limit);}?>
You can combine the article php keyword replacement function, which was previously compiled by Xiaobian, to learn from it. I believe you will have unexpected gains.