Home > Backend Development > PHP Tutorial > PHP string replaces multiple keywords at the same time

PHP string replaces multiple keywords at the same time

WBOY
Release: 2016-07-25 08:49:41
Original
1366 people have browsed it
Replace several keywords in a string at the same time.
It’s really complicated. It should be done with strtr. At that time, I only focused on str_replace. I thought there was no other way and I could ignore this code.
  1. function replace($string,$keyArray,$replacement,$i){
  2. $result='';
  3. if($i<(count($keyArray))){
  4. $strSegArray=explode($keyArray [$i],$string);
  5. foreach ($strSegArray as $index=>$strSeg){
  6. $x=$i+1;
  7. if($index==(count($strSegArray)-1))
  8. $result=$result.replace($strSeg,$keyArray,$replacement,$x);
  9. else
  10. $result=$result.replace($strSeg,$keyArray,$replacement,$x).$replacement[$ i];
  11. }
  12. return $result;
  13. }
  14. else{
  15. return $string;
  16. }
  17. }
  18. $string=' The key name array can contain both integer and string type key names, 12345678 because PHP does not actually Distinguish between indexed arrays and associative arrays.
  19. If no key name is specified for the given value, the current largest integer index value will be 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. ';
  20. $keyArray=array('array','integer','2345','key name');
  21. $replacement=array('AAAA','BBBB','CCCC','DDDD');
  22. echo replace($string,$keyArray,$replacement,0);
Copy code


source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template