This article mainly introduces the php implementation of each keyword only needs to be replaced once, sometimes a project involves the problem of batch replacement of keywords, this article studies the number of control replications, if you are interested, you can refer to the problem of replacing keywords in batches. there is nothing to say about replacement, but here you only need to replace each keyword once. After reading the relevant php function documentation, I found that php itself does not have a function to implement this function, so I have to solve it myself. I have summarized several feasible methods. Please note that!
(1) use the preg_replace function to implement this function. because the preg_replace function can control the number of replicas, you can first think of it. the specific implementation method is as follows:
// The number of replicas can be controlled, not only for one Replacement. for example, if $ limit is 2, it indicates that a word appears many times and only 2 is replaced.-1 indicates that all replicas are replaced. $ Search and $ replace can both be strings or arrays, but must correspond to function str_replace_limit ($ search, $ replace, $ content, $ limit =-1) {if (is_array ($ search) {foreach ($ search as $ k => $ v) {$ search [$ k] = '''. preg_quote ($ search [$ k], '''). ''' ;}} else {$ search = '''. preg_quote ($ search ,'''). ''';} // remove the image description $ content = preg_replace ("/alt = ([^>] +)/is", '', $ content ); return preg_replace ($ search, $ replace, $ content, $ limit );}
(2) use the substr_replace function, but only one replacement can be implemented here.
// First locate the keyword location, and then use substr_replace (system function) to replace function str_replace_once ($ search, $ replace, $ content) {// remove the image description $ content = preg_replace ("/alt = ([^>] +)/is", '', $ content ); $ pos = strpos ($ content, $ search); if ($ pos = false) {return $ haystack;} return substr_replace ($ content, $ replace, $ pos, strlen ($ search ));}
'The above is the implementation function that only replaces PHP once and controls the number of replicas. I hope it will be helpful for everyone.