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, interested friends can refer
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, interested friends can refer
There is nothing to say about replacing keywords in batches, but here we need to replace each keyword only 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:
// You can control the number of replicas, not only for one replacement. For example, if $ limit is set to 2, it indicates that a word appears frequently and only needs to be replaced twice ,, -1 indicates that all 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.