SoFunction
Updated on 2025-03-10

Implementation function that replaces php keyword only once

There is nothing to say about replacing keywords in batches, but what is needed here is that each keyword only needs to be replaced once. After checking the php-related function documentation, I found that php itself does not have a function to implement this function, so I had to solve it myself. I have summarized several feasible methods and take a note!
(1) Use the preg_replace function to implement this function, because the preg_replace function itself can control the number of replacements, so I thought of it from the beginning. The specific implementation method is as follows:

//The number of replacements can be controlled, not only for only one replacement, for example, when $limit is 2, it means that a word appears and eats many times, and -1 means that all replacements are replaced.  $search and $replace can be strings or arrays, but must correspond to them.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 picture description  $content=preg_replace("/alt=([^ >]+)/is",'',$content); 
  return preg_replace($search,$replace,$content,$limit); 
} 

(2) Use the substr_replace function to implement it, but only one replacement can be implemented here

//First find the location of the keyword, and then use substr_replace (system function) to replace itfunction str_replace_once($search,$replace,$content){ 
  // Remove the picture 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 replacements. I hope it will be helpful to everyone's learning.