Home  >  Article  >  Backend Development  >  Implementation function that only replaces php keywords once, php keyword replacement function_PHP tutorial

Implementation function that only replaces php keywords once, php keyword replacement function_PHP tutorial

WBOY
WBOYOriginal
2016-07-12 09:06:00754browse

An implementation function for php keyword replacement only once, php keyword replacement function

For the problem of batch replacement of keywords, there is nothing to say about replacement only, but it is needed here The best thing is that each keyword only needs to be replaced once. I checked the PHP related function documentation and found that PHP itself has no function to implement this function, so I had to solve it myself. We have summarized several possible methods, take a few notes!
(1) Use the preg_replace function to implement this function. Because the preg_replace function itself can control the number of replacements, I thought of it from the beginning. The specific implementation method is as follows:

//可以实现替换次数的控制,不仅限于只替换一次,比如$limit为2的时候表示一个词出现很多吃的时候仅替换2次,-1表示全部替换。$search 和 $replace 都可以是字符串或者数组,但必须对应 
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,'`').'`'; 
  } 
  //把图片描述去掉 
  $content=preg_replace("/alt=([^ >]+)/is",'',$content); 
  return preg_replace($search,$replace,$content,$limit); 
} 

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

//首先找到关键字所在位置,然后使用 substr_replace(系统函数)进行替换操作 
function str_replace_once($search,$replace,$content){ 
  //把图片描述去掉 
  $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 of PHP to only replace once and control the number of replacements. I hope it will be helpful to everyone's learning.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1066509.htmlTechArticleAn implementation function that only replaces php keywords once. The php keyword replacement function only replaces keywords in batches. Not much to say in terms of substitutions, but what is needed here is that each keyword is only...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn