Home  >  Article  >  Backend Development  >  PHP string replacement function can replace multiple keywords at the same time

PHP string replacement function can replace multiple keywords at the same time

WBOY
WBOYOriginal
2016-07-25 08:55:401408browse
  1. /**
  2. * String replacement function
  3. * edit: bbs.it-home.org
  4. */
  5. function replace($string,$keyArray,$replacement,$i){
  6. $result='';
  7. if($i<(count ($keyArray))){
  8. $strSegArray=explode($keyArray[$i],$string);
  9. foreach ($strSegArray as $index=>$strSeg){
  10. $x=$i+1;
  11. if ($index==(count($strSegArray)-1))
  12. $result=$result.replace($strSeg,$keyArray,$replacement,$x);
  13. else
  14. $result=$result.replace($strSeg ,$keyArray,$replacement,$x).$replacement[$i];
  15. }
  16. return $result;
  17. }
  18. else{
  19. return $string;
  20. }
  21. }
Copy code

Code description: $string=' key name array can contain both integer and string type key names, 12345678 because PHP does not actually distinguish between index arrays and associative arrays. If no key is specified for the given value, the current largest integer index value is taken, and the new key name will be that value plus one. If the specified key name already has a value, the value will be overwritten. '; Example:

  1. $keyArray=array('array','integer','2345','key name');
  2. $replacement=array('AAAA','BBBB','CCCC','DDDD' );
  3. echo replace($string,$keyArray,$replacement,0);
Copy code


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